argparse 模块(一)

来源:互联网 发布:淘宝返利红包链接 编辑:程序博客网 时间:2024/05/16 06:32
class argparse.ArgumentParser(prog=Noneusage=Nonedescription=None,epilog=Noneparents=[]formatter_class=argparse.HelpFormatterprefix_chars='-',fromfile_prefix_chars=Noneargument_default=Noneconflict_handler='error',add_help=True)

Create a new ArgumentParser object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:

  • prog - 设置程序名称
  • usage - 程序用法的字符串 (默认情况下,它根据parse的paramer 自动生成)
  • description - 程序描述字符串 (default: none)
  • epilog - 显示在程序帮助信息下的字符串 (default: none)
  • parents - 一个 ArgumentParser 对象的列表,这些ArugmentParser的 参数信息将被添加到此parser中
  • formatter_class - 可自定义hepl的输出信息,有四个现成的class
  •     class argparse.RawDescriptionHelpFormatter   不格式化description 和epilog的字符串
        class argparse.RawTextHelpFormatter          保留help信息中的所有空格
        class argparse.ArgumentDefaultsHelpFormatter默认使用的formatter_class
        class argparse.MetavarTypeHelpFormatter      在help信息中现实参数的类型,而不是参数名

  • prefix_chars - 参数前缀 (default: ‘-‘)
  • fromfile_prefix_chars - 文件名前缀(即后面跟文件名路径,参数将从此文件中读取) (default: None)
  • argument_default - The global default value for arguments (default: None)
  • conflict_handler - 默认情况下,不允许有相同的参数。将此参数设置为'resolve',则后写的参数可以覆盖之前相同的参数 (usually unnecessary)
  • add_help - 是否添加help参数的信息 (default: True)


ArgumentParser.add_argument(name or flags...[action][nargs][const][default][,type][choices][required][help][metavar][dest])

Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:

  • name or flags - 参数名, e.g. foo or -f, --foo.
  • action - 遇到对应参数时采取的动作,
  •     ‘store’:默认值,保存传入的参数值
  •     ‘store_const':保存const 参数指定的值
  •     'store_true' and 'store_false' :值为True或False
  •     ’append‘:值为列表,将这个参数重复指定的值放到一个列表里面
  •     ’append_const‘:值为列表,将参数重复指定的值放到const参数指定的列表里面
  •     ’count‘:值为参数出现的次数
  •     ’help‘:打印所有参数的完整help信息,然后退出。默认情况下help  action自动添加到parser
  •     ’version‘:其后 需要再加一个version=关键字,打印版本信息,然后退出
  •     你也可以设置为自己定义的action,简单的方法就是继承argparse.Action类。
  • nargs - 指明这个参数对应命令行中多少参数.
  •     ’N‘:N个参数将被添加到一个列表作为此参数的值
  •     ’?’:如果此参数出现,它的值为命令行指定的值。如果此参数没出现,则值为default 关键字
  • 指定的值,如果此参数出现,但命令行中没有指定值,则此参数值为 const关键字指定的值
  •     ‘*’:命令后中,此参数后面的值添加到一个列表里面,作为此参数的值
  •     ‘+’:和‘*’ 类似,不同的是,命令行中此参数后不可为空,否则有错误提示
  •     argparse.REMAINDER:命令行中所有其他的参赛,添加到一个列表作为此参数的值
  • const - A constant value required by some action and nargs selections.
  • default - The value produced if the argument is absent from the command line.
  •     argparse.SUPPRESS:当设置default为此值时,所有未出现的参数将不会作为属性添加到Namespace
  • type - The type to which the command-line argument should be converted.
  • >> parser = argparse.ArgumentParser()>>> parser.add_argument('foo', type=int)>>> parser.add_argument('bar', type=open)>>> parser.parse_args('2 temp.txt'.split())Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
        type可以为任何可以调用,并且参数为string类型的函数:
  • >>> def perfect_square(string):...     value = int(string)...     sqrt = math.sqrt(value)...     if sqrt != int(sqrt):...         msg = "%r is not a perfect square" % string...         raise argparse.ArgumentTypeError(msg)...     return value...>>> parser = argparse.ArgumentParser(prog='PROG')>>> parser.add_argument('foo', type=perfect_square)>>> parser.parse_args('9'.split())Namespace(foo=9)>>> parser.parse_args('7'.split())usage: PROG [-h] fooPROG: error: argument foo: '7' is not a perfect square

  • choices - 限制参数的取值范围,为一个列表.
  • required - 可选参数是否必须出现,默认为False,设置为True,则命令后中必须有可选参数。很奇怪的关键字(optionals only).
  • help - 参数的简单描述字符串
  • >>> parser = argparse.ArgumentParser(prog='frobble')>>> parser.add_argument('bar', nargs='?', type=int, default=42,...         help='the bar to %(prog)s (default: %(default)s)')>>> parser.print_help()

  • metavar -When ArgumentParser generates help messages, it needs some way to refer to each expected argument. By default, ArgumentParser objects use the dest value as the “name” of each object. By default, for positional argument actions, the dest value is used directly, and for optional argument actions, the dest value is uppercased. So, a single positional argument with dest='bar' will be referred to as bar. A single optional argument --foo that should be followed by a single command-line argument will be referred to as FOO. An example:
  • >>> parser = argparse.ArgumentParser()>>> parser.add_argument('--foo')>>> parser.add_argument('bar')>>> parser.parse_args('X --foo Y'.split())Namespace(bar='X', foo='Y')>>> parser.print_help()usage:  [-h] [--foo FOO] barpositional arguments: baroptional arguments: -h, --help  show this help message and exit --foo FOO

  • dest - The name of the attribute to be added to the object returned byparse_args().设置parser的属性名。



原创粉丝点击