对于多种情况,在 argparse 中仅使用一个参数

Using only one argument in argparse for multiple cases

$ script.py status
$ script.py terminate
$ script.py tail /tmp/some.log

如您所见,脚本可以执行 3 个任务。最后一个任务需要一个额外的参数(文件的路径)。

我只想使用 add_argument 一次,如下所示。

parser.add_argument("command")

然后检查用户请求的命令,并根据相同的条件创建条件。如果命令是 tail 我需要访问下一个参数(文件路径)

您可能需要为每个命令创建一个 sub-parser。这样,如果其他命令在某些时候也需要参数,那么它是可扩展的。像这样:

import argparse

parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', action='store_true', help='global optional argument')
subparsers = parser.add_subparsers(dest="command", help='sub-command help')

# create the parser for the "status" command
parser_status = subparsers.add_parser('status', help='status help')

# create the parser for the "tail" command
parser_tail = subparsers.add_parser('tail', help='tail help')
parser_tail.add_argument('path', help='path to log')

print parser.parse_args()

add_subparsersdest 关键字确保您之后仍然可以获取命令名称,如 here 和文档中所述。

用法示例:

$ python script.py status   
Namespace(command='status', foo=False)

$ python script.py tail /tmp/some.log
Namespace(command='tail', foo=False, path='/tmp/some.log')

请注意,任何全局参数都需要位于命令之前:

$ python script.py tail /tmp/some.log --foo
usage: PROG [-h] [--foo] {status,tail} ...
PROG: error: unrecognized arguments: --foo

$ python script.py --foo tail /tmp/some.log
Namespace(command='tail', foo=True, path='/tmp/some.log')