更新时间:2023-12-06 17:02:40
subcommands
的文档给出了两个如何标识子解析器的示例.
The documentation for subcommands
gives two examples of how to identify the subparser.
https://docs.python.org/dev/library/argparse.html#sub-commands
一种是给add_subparsers
一个dest
:
def do_quit(args):
# action
quit()
parser = ArgumentParser()
subparser = parser.add_subparsers(dest='cmd')
....
subparser.add_parser('quit')
...
args = parser.parse_args()
print args.cmd # displays 'quit'
if args.cmd == 'quit':
do_quit(args)
另一种方法是使用set_defaults
将子解析器与函数链接:
the other is to use set_defaults
to link the subparser with a function:
parser = ArgumentParser()
subparsers = parser.add_subparsers()
...
parser_quit = subparsers.add_parser('quit')
parser_quit.set_defaults(func=do_quit)
...
args = parser.parse_args()
args.func(args)
进一步考虑,这是使用自定义Action
的一种方法.就像_HelpAction
(由-h
使用).它由带有nargs=0
(或'?')的位置参数调用.即使没有与之匹配的字符串(或更确切地说,有0个字符串与之匹配),也始终会调用这样的参数.这是如何处理位置的合乎逻辑的结果,但有些晦涩.
On further thought, here's a way, using a custom Action
. It is like _HelpAction
(which is used by a -h
). It's called by a positional argument with nargs=0
(or '?'). Such an argument is always called, even though there are no strings to match it (or rather, 0 strings match it). This a logical, but somewhat obscure, consequence of how positionals are handled.
class QuitAction(argparse.Action):
def __call__(self, parser, *args, **kwargs):
parser.exit(message="QUITTING\n")
p=argparse.ArgumentParser()
sp=p.add_subparsers(dest='cmd')
p1=sp.add_parser('quit')
p1.add_argument('foo', action=QuitAction, nargs='?', help=argparse.SUPPRESS)
p.parse_args(['quit'])
生产(在Ipython中运行时):
producing (when run in Ipython):
QUITTING
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0