PytorchCNN project construction 2---Argparse

The overall code can be viewed on my github

The argparse module makes it easy to write user-friendly command-line interfaces.

The program defines the parameters it needs, and then argparse will figure out how to parse those parameters from sys.argv.

The argparse module will also automatically generate help and manuals, and report error messages when the user passes in invalid parameters to the program.

import argparse

Location parameter introduction

"""一个简单的例子"""
## 此程序需要在命令行运行,然后查看相应的结果
parser = argparse.ArgumentParser()
parser.add_argument('echo', help='echo the string you use here')
args = parser.parse_args()
print(args.echo)

1

Description of program operation results:

  • The add_argument() method is used, which is used to specify which command options the program can accept. In this example, the option is named echo , the function is consistent with it, and help is used to illustrate the role of this parameter
  • Now when calling the program, an option must be specified
  • The parser_args() method will actually return the specific data in the options. In this example, echo is returned
'''例子2'''
parser = argparse.ArgumentParser()
parser.add_argument('square', help='display a square of a given number')
args = parser.parse_args()
print(args.square**2)

Optional parameter introduction

parser = argparse.ArgumentParser()
parser.add_argument('--verbosity', '-v', help='increase output verbosity')
args = parser.parse_args()
if args.verbosity:
    print('verbosity turned on')

Insert picture description here

Program description:

  • When the program is designed to specify the -verbosity parameter to display something, otherwise it will not display
  • When this option is not added, the program exits without prompting any error, indicating that the parameter is optional. But it will be displayed in the help information
  • When using –verbosity , some value must be specified
  • The appeal example Jie Ge, any integer value is used as the parameter of –verbosity , but for our simple program, there are only two practical meanings, True or False . Modify the program as follows:

Let's modify this example, add the action parameter, and simplify the -verbosit to -v . In the command line, using these two is the same.

parser = argparse.ArgumentParser()
parser.add_argument('-v','--verbosity', help='increase output verbosity', action='store_true') #默认为True
args = parser.parse_args()

if args.verbose:
    print("verbosity turned on")

Combining positional parameters and optional parameters

parser = argparse.ArgumentParser()
parser.add_argument('square', type=int, help='display a square of a given number')
parser.add_argument('-v', '--verbosity', action='store_true', help='increase output verbosity')
args = parser.parse_args()
answer = args.square ** 2
if args.verbosity:
    print('the square of {} equals {}'.format(args.square, answer))
else:
    print(answer)

Insert picture description here

Add some more complex functions:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choice=[0, 1, 2], default=0, # 限制verbosity的值,并设置默认值
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

It can be seen from the above that the argparse module is a very simple module, but in fact there are many optional parameters. You can check and learn by yourself in the future study.

Finally, I set the parameters that I need to use in the subsequent program and encapsulate it into a function, as shown below:

def parser():
    parse = argparse.ArgumentParser(description='Pytorch Cifar10 Training') 
    parse.add_argument('--config','-c',default='./config/config.py',help='config file path') #设置config参数
    parse.add_argument('--net','-n',type=str,required=True,help='input which model to use') #设置选择进行训练的model类型
    parse.add_argument('--pretrain','-p',action='store_true',help='Location pretrain data') #设置模型是否进行预训练
    parse.add_argument('--resume','-r',action='store_true',help='resume from checkpoint') #设置模型是否进行断点续训
    parse.add_argument('--epoch','-e',default=None,help='resume from epoch') #设置从哪个epoch进行断点续训
    parse.add_argument('--gpuid','-g',type=int,default=0,help='GPU ID') #设置使用的GPU_ID
    args = parse.parse_args()
    return args 

references

Python official website learning tutorial

Finally, I would like to thank my brother, who taught me to build the whole project and the little friends who studied together in the laboratory~ I hope they will succeed in everything, and they will have a great future!

Guess you like

Origin blog.csdn.net/qq_44783177/article/details/113746570