Python argparse切换标志 [英] Python argparse toggle flags

查看:67
本文介绍了Python argparse切换标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

argparse中是否可以解析诸如[+-]a,b,c,d之类的标志?

Is there any way in argparse to parse flags like [+-]a,b,c,d?

foo.py +s -b

应该将sdest中的True存储在bdest中,将False存储在Windows attrib或Linux chmod中.

should store True in the dest of s and False in the dest of b, much like done by the Windows attrib or the Linux chmod.

当前,我分别使用2个单独的参数+s-s以及store_truestore_false.但这会给每个标志两次列出一个丑陋的帮助(+ a&-a)

Currently, I am using 2 separate arguments +s and -s with store_true and store_false, respectively. But it creates an ugly help with it listing each flag twice (+a & -a)

另一种解决方法是使用正则表达式手动解析扩展的arg(这似乎要容易得多,并且使用自定义描述,但是,在此之前,我只是想看看是否有使用它的东西我可以使用argparse本身执行相同的操作.

Another workaround would be to manually parse the extended arg with regex (which somehow seems a lot easier and use custom description, but before doing that I just wanted to look around if there was anything using which I could perform the same thing using argparse itself.

推荐答案

您可以通过将-s+s都传递给单个add_argument调用并使用自定义操作来实现:

You can do this by passing both -s and +s to a single add_argument call, and using a custom action:

class ToggleAction(argparse.Action):
    def __call__(self, parser, ns, values, option):
        setattr(ns, self.dest, bool("-+".index(option[0])))
ap = ArgumentParser(prefix_chars='-+')
ap.add_argument('-s', '+s', action=ToggleAction, nargs=0)

ap.parse_args(['+s'])
Namespace(s=True)

ap.parse_args(['-s'])
Namespace(s=False)

这篇关于Python argparse切换标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆