argparse模块-ArgumentParser对象

2020-05-12  本文已影响0人  一技破万法

argparse 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数,然后 argparse 将弄清如何从 sys.argv 解析出那些参数。 argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。

创建一个解析器

创建一个ArgumentParser对象:

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

ArgumentParser 对象包含将命令行解析成 Python 数据类型所需的全部信息。

添加参数

给ArgumentParser添加程序参数信息是通过调用add_argument()方法完成的。这些信息在parse_args()调用时被存储和使用。

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)')

稍后,调用parse_args()将返回一个具有integers和accumulate两个属性的对象。integers 属性将是一个包含一个或多个整数的列表,而accumulate属性当命令行中指定了 --sum参数时将是sum() 参数时将是sum()函数,否则是max()函数。

解析参数

ArgumentParser通过parse_arg()方法解析参数。它将检查命令行,把每个参数转换为适当的类型然后调用相应的操作。在大多数情况下,这意味着一个简单的Namespace对象将从命令行参数中解析出的属性构建:

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

在脚本中,通常parse_args()会被不带参数调用,而ArgumentParser将自动从sys.argv确定命令行参数。

ArgumentPaeser 对象

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)
创建一个新的ArgumentPaeser对象。所有的参数都应当作为关键字参数传入。




prog

默认情况下,ArgumentParser 对象使用 sys.argv[0] 来确定如何在帮助消息中显示程序名称。这一默认值几乎总是可取的,因为它将使帮助消息与从命令行调用此程序的方式相匹配。例如,对于有如下代码的名为 myprogram.py 的文件:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

该程序的帮助信息将显示 myprogram.py 作为程序名称(无论程序从何处被调用):

python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

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

通过使用prog=参数为ArgumentParser提供另一个值(只改变程序名称)。

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.print_help()
usage: myprogram [-h]
optional arguments:
 -h, --help  show this help message and exit

需要注意的是,无论是从sys.argv[0]或是从prog=参数确定的程序名称,都可以通过 %(prog)s格式串来引用。

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
---

usage

ArgumentParser根据它包含的参数来构建用法消息:

>>> 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

通过添加usage=关键词参数覆盖这一默认消息:

>>>parser = argparse.ArgumentParser(prog = 'PROG', usage = '%(prog)s [options]'))
>>>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
---
#### description
简要描述程序做法
```parser = argparse.ArgumentParser(description = 'A foo that bars')
    parser = print_help()
usage: argparse.py [-h]

A foo that bars

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
有些时候,少数解析器会使用同一系列参数。 单个解析器能够通过提供 `parents=` 参数给 [`ArgumentParser`](https://docs.python.org/zh-cn/3/library/argparse.html#argparse.ArgumentParser "argparse.ArgumentParser") 而使用相同的参数而不是重复这些参数的定义。`parents=` 参数使用 [`ArgumentParser`](https://docs.python.org/zh-cn/3/library/argparse.html#argparse.ArgumentParser "argparse.ArgumentParser") 对象的列表,从它们那里收集所有的位置和可选的行为,然后将这写行为加到正在构建的 [`ArgumentParser`](https://docs.python.org/zh-cn/3/library/argparse.html#argparse.ArgumentParser "argparse.ArgumentParser") 对象。

parent_parser.add_argument('--parent', type=int)

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

bar_parser = argparse.ArgumentParser(parents=[parent_parser])
bar_parser.add_argument('--bar')
bar_parser.parse_args(['--bar', 'YYY'])
Namespace(bar='YYY', parent=None)

请注意大多数父解析器会指定 add_help=False . 否则, ArgumentParse 将会看到两个 -h/--help 选项(一个在父参数中一个在子参数中)并且产生一个错误。
>注解 你在传``parents=``给那些解析器时必须完全初始化它们。如果你在子解析器之后改变父解析器是,这些改变不会反映在子解析器上。
---
#### prefix_chars
解析器需要不同或额外的字符,可以在参数解析构建器中使用prefix_chars=参数。

parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
parser.add_argument('+f')
parser.add_argument('++bar')
parser.parse_args('+f X ++bar Y'.split())
Namespace(bar='Y', f='X')

>The prefix_chars= 参数默认使用 '-'. 支持一系列字符,但是不包括 - ,这样会产生不被允许的 -f/--foo 选项。
---
#### fromfile_prefix_chars
将参数存入文件中,然后使用函数调用。

with open('args.txt', 'w') as fp:
... fp.write('-f\nbar')
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('-f')
parser.parse_args(['-f', 'foo', '@args.txt'])
Namespace(f='bar')

---
####argument_default
---
####conflict_handler
当conflict_hander=resolve时,ArgumentParser对象可以在相同选项字符串下有两种行为,但是只能移除一个行为。

parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
parser.add_argument('-f', '--foo', help='old foo help')
parser.add_argument('--foo', help='new foo help')
parser.print_help()
usage: PROG [-h] [-f FOO] [--foo FOO]
optional arguments:
-h, --help show this help message and exit
-f FOO old foo help
--foo FOO new foo help

了解更多请关注作者微信公众号:

一技破万法
上一篇 下一篇

猜你喜欢

热点阅读