Python argparse --toggle --no-toggle 标志 [英] Python argparse --toggle --no-toggle flag
问题描述
是否有一种直接的方法可以在 Python 的 argparse 中使用 --toggle
和 --no-toggle
标志?
现在我正在使用类似于以下内容的内容:
导入 argparse解析器 = argparse.ArgumentParser()parser.add_argument('--toggle',动作='store_true',dest='切换')parser.add_argument('--no-toggle',动作='store_true',默认=真,dest='notoggle')options = parser.parse_args([])
我只是手动解析长 if 链中的可能性,但是如果有一种方法可以整理它并让解析器立即将状态存储在一个目的地,例如options.toggle
.这是否可行?如果可行,如何操作?
一个有点相关的答案是 Python argparse 切换标志 但是我有兴趣使用 --no-
作为 longopts store_false
切换前缀(类似于上述链接中概述的 -
shortopts 切换前缀).
为什么不和你链接的帖子一样?
导入 argparse类 NegateAction(argparse.Action):def __call__(self, parser, ns, values, option):setattr(ns, self.dest, option[2:4] != 'no')ap = argparse.ArgumentParser()ap.add_argument('--toggle', '--no-toggle', dest='toggle', action=NegateAction, nargs=0)
然后,如果标志的开头有 no
,则将其设置为 False:
Is there a straightforward way to use --toggle
and --no-toggle
flags with Python's argparse?
Right now I'm using something similar to the following:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--toggle',
action='store_true',
dest='toggle')
parser.add_argument('--no-toggle',
action='store_true',
default=True,
dest='notoggle')
options = parser.parse_args([])
I'm just manually parsing out the possibilities in a long if chain, but it would be nice if there was a way to tidy this up and have the state immediately stored in one destination by the parser, e.g. options.toggle
. Is this feasible and if so, how?
A somewhat related answer is Python argparse toggle flags however I'm interested in using --no-
as the longopts store_false
toggle prefix (similar to the -
shortopts toggle prefix outlined in the aforementioned link).
Why not do the same as the post you linked to??
import argparse
class NegateAction(argparse.Action):
def __call__(self, parser, ns, values, option):
setattr(ns, self.dest, option[2:4] != 'no')
ap = argparse.ArgumentParser()
ap.add_argument('--toggle', '--no-toggle', dest='toggle', action=NegateAction, nargs=0)
Then if the flag has no
at the beginning it is set to False:
>>> ap.parse_args(['--toggle'])
Namespace(toggle=True)
>>> options = ap.parse_args(['--no-toggle'])
>>> options.toggle
False
这篇关于Python argparse --toggle --no-toggle 标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!