Python argparse.ArgumentParser()用法解析

  argparse是一个Python模块:命令行选项、参数和子命令解析器。作用和C语言中的命令行参数作用相同。
  argparse 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数,然后 argparse 将弄清如何从 sys.argv 解析出那些参数。 argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。
使用流程:
  引入模块–>创建解析器–>添加参数–>解析参数
  
引入模块
  import argparse

创建解析器------ArgumentParser对象
  ap= argparse.ArgumentParser(description=‘Process some integers.’)
  使用 argparse 的第一步是创建一个 ArgumentParser 对象。
ArgumentParser 对象包含将命令行解析成 Python 数据类型所需的全部信息。

ArgumentParser对象
prog - 程序的名称(默认: sys.argv[0],prog猜测是programma的缩写)
usage - 描述程序用途的字符串(默认值:从添加到解析器的参数生成)
description - 在参数帮助文档之后显示的文本 (默认值:无)

添加参数-------add_argument()方法

  添加的方法一是用下面语句设置的默认参数,二是在菜单中的Run–>Edit Configurations里编辑,和C的命令行参数类似。
  ap.add_argument(‘integers’, metavar=‘N’, type=int, nargs=’+’, help=‘an integer for the accumulator’)

add_argument()方法:
name or flags - 一个命名或者一个选项字符串的列表
action - 表示该选项要执行的操作
default - 当参数未在命令行中出现时使用的值
dest - 用来指定参数的位置
type - 为参数类型,例如int
choices - 用来选择输入参数的范围。例如choice = [1, 5, 10], 表示输入参数只能为1,5 或10
help - 用来描述这个选项的作用,给一个 ArgumentParser 添加程序参数信息是通过调用 add_argument() 方法完成的。

解析参数------parser.parse_args()

  把parser中设置的所有"add_argument"给返回到args子类实例当中, 那么parser中增加的属性内容都会在args实例中,使用即可。

使用实例

    parser = argparse.ArgumentParser(description="NN")
    parser.add_argument("-C", "--configuration", required=True, type=str, help="Configuration (*.json).")
    parser.add_argument("-P", "--preloaded_model_path", type=str, help="Path of the *.Pth file of the model.")
    parser.add_argument("-R", "--resume", action="store_true", help="Resume experiment from latest checkpoint.")
    args = parser.parse_args()

    if args.preloaded_model_path:
        assert not args.resume, "Resume conflict with preloaded model. Please use one of them."

おすすめ

転載: blog.csdn.net/u011913417/article/details/109047850