Python argparse切换标志 [英] Python argparse toggle flags
问题描述
argparse中是否可以解析诸如[+-]a,b,c,d
之类的标志?
Is there any way in argparse to parse flags like [+-]a,b,c,d
?
foo.py +s -b
应该将s
的dest
中的True存储在b
的dest
中,将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_true
和store_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屋!