Python argparse toggle flags

偶尔善良 提交于 2019-12-23 07:59:32

问题


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

foo.py +s -b

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.

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)

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.


回答1:


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)


来源:https://stackoverflow.com/questions/11507756/python-argparse-toggle-flags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!