Argparse -- 命令行选项、参数和子命令解析器

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

举个例子:

parser = argparse.ArgumentParser(description='Process some integers.')
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)')

args = parser.parse_args()
print(args.accumulate(args.integers))

假设上面的 Python 代码保存在名为 prog.py 的文件中, 在命令行运行 -h 显示帮助消息:

$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
 N           an integer for the accumulator

optional arguments:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)

当使用适当的参数运行时,它会输出命令行传入整数的总和或者最大值:

$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4 --sum
10

How to:

1. 创建一个解析器

使用 argparse 的第一步是创建一个 ArgumentParser 对象:

parser = argparse.ArgumentParser(description='Process some integers.')
2. 添加参数
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()方法完成的。通常,这些调用指定 ArgumentParser如何获取命令行字符串并将其转换为对象。这些信息在 parse_args() 调用时被存储和使用。

3. 解析参数

ArgumentParser通过 parse_args()方法解析参数。
它将检查命令行,把每个参数转换为适当的类型然后调用相应的操作。
在脚本中,通常 parse_args()会被不带参数调用,而 ArgumentParser 将自动从 sys.argv中确定命令行参数。

函数说明:

  • ArgumentParser(), 创建一个新的 ArgumentParser对象。
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)`

通常会用到 description 这个参数:
argparse.ArgumentParser( Description="xxxxxx")


  • add_argument() , 定义单个的命令行参数应当如何解析.
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
args descriptions
name or flags 一个命名或者一个选项字符串的列表,例如 foo-f, --foo
action 当参数在命令行中出现时使用的动作基本类型。
nargs 命令行参数应当消耗的数目。
const 被一些 actionnargs 选择所需求的常数。
default The value produced if the argument is absent from the command line and if it is absent from the namespace object.
type 命令行参数应当被转换成的类型。
choices 可用的参数的容器。
required 此命令行选项是否可省略 (仅选项可用)。
help 一个此选项作用的简单描述。
metavar 在使用方法消息中使用的参数值示例。
dest 被添加到 parse_args()所返回对象上的属性名。

action :

指定了这个命令行参数应当如何处理。动作的选项有:
store : 存储参数的值 (默认).
store_const : 存储被 const 命名参数指定的值.
store_true or store_false: 这些是 'store_const' 分别用作存储 True 和 False 值的特殊用例.
append: 存储一个列表,并且将每个参数值追加到列表中.
append_const: 存储一个列表,并将 const 命名参数指定的值追加到列表中.
count: 计算一个关键字参数出现的数目或次数.
help: 打印所有当前解析器中的选项和参数的完整帮助信息,然后退出.
version: 期望有一个 version= 命名参数在 add_argument()调用中,并打印版本信息并在调用后退出.
extend: 存储一个列表,并将每个参数值加入到列表中.


  • parse_args(), 将参数字符串转换为对象并将其设为命名空间的属性。 返回带有成员的命名空间。
ArgumentParser.parse_args(args=None, namespace=None)

args - 要解析的字符串列表。 默认值是从 sys.argv获取。
namespace - 用于获取属性的对象。 默认值是一个新的空 Namespace对象。

其他实用工具

  • add_subparsers(), 创建子命令.
    The add_subparsers()method is normally called with no arguments and returns a special action object. This object has a single method, add_parser(), which takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual.

Some example usage:
# create the top-level parser
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', action='store_true', help='foo help')
subparsers = parser.add_subparsers(help='sub-command help')
# create the parser for the "a" command
parser_a = subparsers.add_parser('a', help='a help')
parser_a.add_argument('bar', type=int, help='bar help')
parser.parse_args()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容