python argparse - 向没有参数的子解析器添加操作? [英] python argparse - add action to subparser with no arguments?
问题描述
我正在向我的解析器添加子解析器以模拟子命令功能(例如代码参见:python 中的简单命令行应用程序 - 解析用户输入?).现在我想添加一个 quit
子解析器/命令,它不带参数并且附加了一个退出"操作.是否可以 ?我该怎么办?
I am adding subparsers to my parser to simulate subcommands functionality (for example code see: Simple command line application in python - parse user input?). Now I want to add a quit
subparser/command that takes no arguments and has a "quit" action attached. Is it possible ? How can I go about it ?
推荐答案
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
这篇关于python argparse - 向没有参数的子解析器添加操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!