python找不到自带的argparse_python argparse-在没有参数的情况下向子解析器添加操作?...

这篇博客介绍了如何在Python的argparse模块中为命令行应用添加子命令,特别是如何创建一个不需要参数且关联'quit'动作的子命令。作者通过两种方法展示了实现这一功能的代码示例,包括设置dest属性和使用set_defaults方法。最后,通过创建一个自定义的QuitAction类,实现了当用户输入'quit'时退出程序的功能。
摘要由CSDN通过智能技术生成

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 ?

解决方案

The documentation for subcommands gives two examples of how to identify the subparser.

One is to give the add_subparsers a 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)

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)

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'])

producing (when run in Ipython):

QUITTING

An exception has occurred, use %tb to see the full traceback.

SystemExit: 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值