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,很像done通过 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
.
目前,我分别使用 +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(不知何故似乎更容易并使用自定义描述,但是在此之前我只想环顾四周是否有任何使用 which我可以使用 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屋!