Python argparse --toggle --no-toggle标志 [英] Python argparse --toggle --no-toggle flag

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

问题描述

是否可以通过Python的argparse直接使用--toggle--no-toggle标志?

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([])

我只是在很长的if链中手动解析可能性,但是如果有一种方法可以整理一下并由解析器将状态立即存储在一个目标中,这将是很好的,例如options.toggle.这可行吗?如果可以,怎么办?

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?

某种相关的答案是 Python argparse切换标志,但是我对使用--no-作为longopts store_false切换前缀(类似于上述链接中概述的- shortopts切换前缀).

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)

然后,如果标志开头有no,则将其设置为False:

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屋!

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