python顺序执行 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([])

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值