Introduction to the argparse module

    When running a python program on the server, it is often necessary to enter additional parameters, or hope that these parameters do not need to be changed directly in the code. It is a good way to use the argparse built-in module.

Steps for usage

It only needs 3 steps to complete:

1. Create an object

parser = argparse.ArgumentParser(description='example')

2. Increase the parameters

parser.add_argument('--no-cuda', action='store_true', default=False,
                    help='disables CUDA training')

3, analysis

 

args = parser.parse_args()

print(args.cuda)

Corresponding to argarse, you need to clarify the meaning of the parameters in step 2, beginning with --, indicating optional parameters, if not, you must add them, otherwise an error will be reported.

parser = argparse.ArgumentParser()
parser.add_argument("add", help="display a square of a given number", type=int)
args = parser.parse_args()
print(args.add+2)


Some common usage:

Check if there is a GPU, if there is, turn it on:

parser = argparse.ArgumentParser(description='example')

parser.add_argument('--no-cuda', action='store_true', default=False,
                    help='disables CUDA training')


args = parser.parse_args()

args.cuda = not args.no_cuda and torch.cuda.is_available()

if args.cuda:
    print('\nGPU is ON!')

Set the default parameters of the parameters:

parser.add_argument('--var_bag_length', type=int, default=2, metavar='VL',
                    help='variance of bag length')

--var_bag_length: indicates that the variable name is var_bag_length, which is an optional parameter

type=int: expressed as int type

default=2: means var_bag_length is 2 by default

metavar='VL': Indicates that the usage promotes the user variable to VL

help='variance of bag length': help information

The add_argument() method parameters can be seen in this article

Guess you like

Origin blog.csdn.net/qq_39463175/article/details/108083392