argparse的中文官方文档地址

我错了,找到了中文的官方文档地址了:

https://docs.python.org/zh-cn/dev/library/argparse.html

后面就不写了。悲剧

因为前面的离散事件仿真用到了argparse,这个模块没学过。手头也有Python3标准库的书。就给自己记录下。

还是看官方网址吧:https://docs.python.org/dev/library/argparse.html

那个书实在看不来。

准备用自己就认识ABC的英语水平把这个包全文理解看看。

首先创建一个解释器对象:

parser = argparse.ArgumentParser(description='Process some integers.')

 然后向对象添加一些参数

parser.add_argument('integers', metavar='N', type=int, nargs='+',
...                     help='an integer for the accumulator')

 metavar在help里面会显示该信息,type标识数据类型,(不写默认为str)

nargs

'?'   0或1个参数
'*' 0或所有参数
'+' 所有,并且至少一个参数
parser.add_argument('--sum', dest='accumulate', action='store_const',
...                     const=sum, default=max,
...                     help='sum the integers (default: find the max)')

 dest的内容,可以通过parser.xxx取出对象内容,action为当输入名字时候对象运行的状态,default是默认没有输入名字的时候的状态

parser.parse_args(['--sum', '7', '-1', '42'])

 这个是解析参数,由于在交互模式下,通过列表进行传参。

Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

 返回的结果。由于输入了--sum,所以执行了action,输出const

当如果默认输入的话:

In [53]: parser.parse_args(['7', '-1', '42','13'])                                                              
Out[53]: Namespace(accumulate=<built-in function max>, integers=[13])

 accumulate变成默认的了,但integers确只接收到了一个数字。

后面看下去,现在无法理解。

我就只能翻译一个标题:实例化的时候能填写的参数:

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, allow_abbrev=True, exit_on_error=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 - The name of the program (default: sys.argv[0])

  • usage - The string describing the program usage (default: generated from arguments added to parser)

  • description - Text to display before the argument help (default: none)

  • epilog - Text to display after the argument help (default: none)

  • parents - A list of ArgumentParser objects whose arguments should also be included

  • formatter_class - A class for customizing the help output

  • prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)

  • fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)

  • argument_default - The global default value for arguments (default: None)

  • conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)

  • add_help - Add a -h/--help option to the parser (default: True)

  • allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)

  • exit_on_error - Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True)

Changed in version 3.5: allow_abbrev parameter was added.

Changed in version 3.8: In previous versions, allow_abbrev also disabled grouping of short flags such as -vv to mean -v -v.

Changed in version 3.9: exit_on_error parameter was added.

The following sections describe how each of these are used.

我操,太多了,我看很多就介绍一个description

好在后面有一个案例,我就模拟操作看看。

第一个:prog

就是帮助的时候,提供显示的文字,不论在哪个目录下,都显示该文件名,调用的是sys.args[0]

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
$ cd ..
$ python subdir/myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help

 本目录下,与上级目录下的调用帮助显示,文件名都是一样的。

但我在ipython下,默认的名字给我了一个ipython

In [58]: parser = argparse.ArgumentParser()                                                                     

In [59]: parse.print_help()                                                                                     
usage: ipython [-h]

optional arguments:
  -h, --help  show this help message and exit

 那我手动给他输入一个:

In [60]: >>> parser = argparse.ArgumentParser(prog='myprogram') 
    ...: >>> parser.add_argument('--foo', help='foo of the %(prog)s program') 
    ...: >>> parser.print_help()                                                                                
usage: myprogram [-h] [--foo FOO]

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO   foo of the myprogram program

 通过示例可以看出,输入了prog以后可以显示,而且不管你是否使用了prog,都可以使用%(prog)格式化输出。

实际测试很好用。

import argparse
parser = argparse.ArgumentParser(prog='hello')
parser.add_argument('--foo', help='foo help')
parser.add_argument('-xfoo', help='foo of the %(prog)s program') 
args = parser.parse_args()
usage: hello [-h] [--foo FOO] [-xfoo XFOO]

optional arguments:
  -h, --help  show this help message and exit
  --foo FOO   foo help
  -xfoo XFOO  foo of the hello program

 usage,就是把你默认的第一排显示的信息,你可以格式化以后重新输出。

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [-h] [--foo [FOO]] bar [bar ...]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help

 默认情况下,第一行就包括了他所有的参数用法信息。

In [61]:  parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') 
    ...: >>> parser.add_argument('--foo', nargs='?', help='foo help') 
    ...: >>> parser.add_argument('bar', nargs='+', help='bar help') 
    ...: >>> parser.print_help()                                                                                
usage: PROG [options]

positional arguments:
  bar          bar help

optional arguments:
  -h, --help   show this help message and exit
  --foo [FOO]  foo help

 上面就是usage重新格式化输出后的信息,就输出的第一行信息发生了一些变化。

description

这个没啥好介绍的,描述么,就把你的项目大概的意思稍微写一下就好了。

In [10]: parser = argparse.ArgumentParser(description='我是傻逼')                                  

In [11]: parser.print_help()                                                                       
usage: ipython [-h]

我是傻逼

optional arguments:
  -h, --help  show this help message and exit

 介绍一下自己,后面这个位置还可以调整。

epilog

结束语,就是最后面显示的,当然也可以通过后面学习调整一下位置。

>>> parser = argparse.ArgumentParser(
...     description='A foo that bars',
...     epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit

And that's how you'd foo a bar

parents

你的父类,这个跟类一样可以继承。

In [32]: parent_parser = argparse.ArgumentParser(add_help=False)                                   

In [33]: parent_parser.add_argument('--parent', type=int)                                          
Out[33]: _StoreAction(option_strings=['--parent'], dest='parent', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)

In [34]: foo_parser = argparse.ArgumentParser(parents=[parent_parser]) 
    ...: >>> foo_parser.add_argument('foo') 
    ...: >>> foo_parser.parse_args(['--parent', '2', 'XXX'])                                       
Out[34]: Namespace(foo='XXX', parent=2)

 在这里,父解释器必须把add_help设置为False,要么子解释器也有help会有冲突。

还有一点提醒,父解释器的一些参数必须在子解释器继承之前添加,要不然后面添加的信息,子解释器无法继承到。

从parent=[],列表可以看出来,应该可以继承多个父解释器。

原文地址:https://www.cnblogs.com/sidianok/p/12166914.html