在argparse中只使用一个参数用于多个案例

时间:2018-02-15 07:57:58

标签: python python-2.7 argparse

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

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

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

parser.add_argument("command")

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

1 个答案:

答案 0 :(得分:1)

您可能必须为每个命令创建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()

dest的{​​{1}}关键字确保您仍然可以获得命令名称,如here和文档中所述。

使用示例:

add_subparsers

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

$ 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')
相关问题