Home > Backend Development > Python Tutorial > Using Python argparse: How to handle command line arguments

Using Python argparse: How to handle command line arguments

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-04-22 15:28:18
forward
1245 people have browsed it

    1. Preface

    argparse is a command line parameter parsing package for python. It is convenient to use when the code needs to frequently modify parameters. The main usage is Enter the parameters you want to modify on the command line.

    2. Common frameworks for argparse usage

    import argparse
    
    def get_parser():
    
        # argparse.ArgumentParser生成argparse对象 description为描述信息,当在命令行输入需要显示帮助信息时,会显示
    
        parser = argparse.ArgumentParser(description="pytorch unet training")
    
        # 路径参数设置 help为参数的帮助信息
    
        parser.add_argument("--data_path", default="./", help="DRIVE root")
    
        # 预测类别数量 type如果不指定需要输入的是str类型
    
        parser.add_argument("--num_classes", default=1, type=int)
    
        # 指定设备使用
    
        parser.add_argument("--device", default="cuda", help="training device")
    
        # 指定batch size大小 "-b", "--batch_size"表示两个都可以在命令行使用
    
        parser.add_argument("-b", "--batch_size", default=4, type=int)
    
        return parser
    
    if __name__ =='__main__':
    
        parser = get_parser()
    
        args = parser.parse_args()
    
        print(args)
    Copy after login

    As mentioned above, get_parser() is some of the usage methods introduced in this article. This python file is called python_argparse_test1.py, in which

    parser = argparse.ArgumentParser(description="pytorch unet training") is used to create a parser object

    add_argument() is used to add parameters

    args = parse_args() in parser.parse_args() to obtain parsing Parameters

    1. Get the parameter list

    When python python_argparse_test1.py is entered on the command line, print the parameters obtained by args and get:

    Namespace(batch_size=4, data_path ='./', device='cuda', num_classes=1)

    Indicates the parameter list parsed by this parameter parser

    2. Get help information

    Input python python_argparse_test1.py -h or python python_argparse_test1.py --help displays information, where usage shows its usage, pytorch unet training is the description when creating the object, and below is the information and usage of each parameter

    Using Python argparse: How to handle command line arguments

    3. Command line modification parameters

    import argparse
    
    def get_parser():
    
        # argparse.ArgumentParser生成argparse对象 description为描述信息,当在命令行输入需要显示帮助信息时,会显示
    
        parser = argparse.ArgumentParser(description="pytorch unet training")
    
        # 路径参数设置 help为参数的帮助信息 default为默认参数
    
        parser.add_argument("--data_path", default="./", help="DRIVE root")
    
        # 预测类别数量 type如果不指定需要输入的是str类型
    
        parser.add_argument("--num_classes", default=1, type=int)
    
        # 指定设备使用
    
        parser.add_argument("--device", default="cuda", help="training device")
    
        # 指定batch size大小 "-b", "--batch_size"表示两个都可以在命令行使用
    
        parser.add_argument("-b", "--batch_size", default=4, type=int)
    
        return parser
    
    if __name__ =='__main__':
    
        parser = get_parser()
    
        args = parser.parse_args()
    
        print("data_path: ",args.data_path)
    
        print("num_classes: ", args.num_classes)
    Copy after login

    Command line input: python python_argparse_test1.py --data_path Desktop --num_classer 4, the result is as follows:

    data_path: Desktop

    num_classes: 4

    You can see that the parameters have been modified through the command line

    4. The use of '_' and "__"

    if __name__ =='__main__':
    
        parser = get_parser()
    
        args = parser.parse_args()
    
        print("-b: ",args.b)
    
        print("--batch_size: ", args.batch_size)
    Copy after login

    Enter python python_argparse_test1.py -b 10 --batch_size 20 on the command line, and an error will be reported:

    Using Python argparse: How to handle command line arguments

    This is because when '_' and '__' exist at the same time, The system defaults to the parameter name

    . Change the above code to:

    if __name__ =='__main__':
    
        parser = get_parser()
    
        args = parser.parse_args()
    
        print("--batch_size: ",args.batch_size)
    Copy after login

    but the command line will not be affected. Continue to execute the command python python_argparse_test1.py -b 10 to get:

    --batch_size: 10

    5. Type usage

    type will force the input command line characters to be converted into type type

    if __name__ =='__main__':
    
        parser = get_parser()
    
        args = parser.parse_args()
    
        print("--batch_size type: ",type(args.batch_size))
    Copy after login

    Command line input: python python_argparse_test1 .py --batch_size '10' gets:

    --batch_size type:

    6.required: used to indicate whether this parameter needs to be provided

    parser.add_argument("--num_classes", default=1, type=int, required=True)
    Copy after login

    If you enter the command python python_argparse_test1.py

    This will report an error prompting the parameters that are indeed required

    python_argparse_test1.py: error: the following arguments are required: --num_classes

    7.choicesSelect parameters

    parser.add_argument('-arch', required=True, choices=['alexnet', 'vgg'])
    Copy after login

    If you run the command: python python_argparse_test1.py -arch cnn

    This will report an error

    python_argparse_test1.py: error: argument - arch: invalid choice: 'cnn' (choose from 'alexnet', 'vgg')

    The above is the detailed content of Using Python argparse: How to handle command line arguments. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template