Learning Python(6)--Python的命令行解析argparse模块

来源:互联网 发布:淘宝口令是什么意思啊 编辑:程序博客网 时间:2024/05/21 13:45

argparse模块官方文档:https://docs.python.org/2/library/argparse.html

Creating a parser

创建一个解析对象

parser = argparse.ArgumentParser(description='Process some integers.')
一般只需要传入description参数。

class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)

Adding arguments

向该解析对象中添加你要关注的命令行参数和选项,每一个add_argument方法对应一个你要关注的参数或选项。

parser.add_argument('integers', metavar='N', type=int, nargs='+',                    help='an integer for the accumulator')parser.add_argument('--sum', dest='accumulate',action='store_const',                const=sum, default=max,                help='sum the integers (default: find the max)')

函数原型:

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
  • name or flags - Either a name or a list of option strings, e.g. foo or -f, –foo.参数有两种,可选参数和位置参数。
  • action - The basic type of action to be taken when this argument is encountered at the command line.默认为store
  • nargs - The number of command-line arguments that should be consumed.参数的数量。值可以为整数N(N个),*(任意多个),+(一个或更多)。值为?时,首先从命令行获得参数,若没有则从const获得,然后从default获得
  • const - A constant value required by some action and nargs selections.保存一个常量
  • default - The value produced if the argument is absent from the command line.默认值
  • type - The type to which the command-line argument should be converted.参数类型
  • choices - A container of the allowable values for the argument.可供选择的值
  • required - Whether or not the command-line option may be omitted (optionals only).是否必选
  • help - A brief description of what the argument does.
  • metavar - A name for the argument in usage messages.
  • dest - The name of the attribute to be added to the object returned by parse_args().可作为参数名

Parsing arguments

调用parse_args()方法进行解析;解析成功之后即可使用

0 0
原创粉丝点击