Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #22121

argparse ConfigureAction problem

Path csiph.com!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!feeds.phibee-telecom.net!newsfeed.xs4all.nl!newsfeed5.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail
Return-Path <python-python-list@m.gmane.org>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'example:': 0.03; 'elif': 0.04; 'value,': 0.04; 'parser': 0.05; 'below).': 0.07; 'none:': 0.07; 'argument,': 0.09; 'assert': 0.09; 'assumed': 0.09; 'positional': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'string)': 0.09; 'value:': 0.09; 'error:': 0.10; 'def': 0.13; 'argument': 0.15; 'arg': 0.16; 'argparse': 0.16; 'boolean': 0.16; 'namespace,': 0.16; 'parser,': 0.16; 'subject:argparse': 0.16; 'suffix': 0.16; 'subject:problem': 0.19; '(which': 0.19; "doesn't": 0.22; 'optional': 0.23; 'string': 0.24; 'fix': 0.25; 'import': 0.27; 'raise': 0.28; 'invalid': 0.28; 'class': 0.29; "skip:' 10": 0.29; 'problem': 0.29; 'skip:p 30': 0.29; 'arguments.': 0.30; 'value)': 0.30; "i've": 0.32; 'this.': 0.33; 'header:User-Agent:1': 0.33; 'header:X-Complaints-To:1': 0.34; 'to:addr:python-list': 0.35; 'received:org': 0.36; 'using': 0.37; 'skip:- 40': 0.38; 'skip:_ 10': 0.38; 'skip:o 20': 0.38; 'but,': 0.39; 'skip:- 50': 0.39; 'to:addr:python.org': 0.40; 'skip:s 40': 0.40; 'here': 0.64; 'subject:skip:C 10': 0.64; "'f',": 0.84
X-Injected-Via-Gmane http://gmane.org/
To python-list@python.org
From Neal Becker <ndbecker2@gmail.com>
Subject argparse ConfigureAction problem
Date Sat, 24 Mar 2012 14:30:09 -0400
Mime-Version 1.0
Content-Type text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding 7Bit
X-Gmane-NNTP-Posting-Host c-68-33-202-49.hsd1.md.comcast.net
User-Agent KNode/4.8.1
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.12
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.955.1332613827.3037.python-list@python.org> (permalink)
Lines 82
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1332613827 news.xs4all.nl 6843 [2001:888:2000:d::a6]:44055
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:22121

Show key headers only | View raw


I've been using arparse with ConfigureAction (which is shown below).  But, it 
doesn't play well with positional arguments.  For example:

./plot_stuff2.py --plot stuff1 stuff2
[...]
plot_stuff2.py: error: argument --plot/--with-plot/--enable-plot/--no-plot/--
without-plot/--disable-plot: invalid boolean value: 'stuff1'

Problem is --plot takes an optional argument, and so the positional arg is 
assumed to be the arg to --plot.  Not sure how to fix this.


Here is the parser code:

    parser = argparse.ArgumentParser()

[...]
    parser.add_argument ('--plot', action=ConfigureAction, default=False)
    parser.add_argument ('files', nargs='*')
    
    opt = parser.parse_args(cmdline[1:])

Here is ConfigureAction:

-----------------------------------------------------
import argparse
import re


def boolean(string):
    string = string.lower()
    if string in ['0', 'f', 'false', 'no', 'off']:
        return False
    elif string in ['1', 't', 'true', 'yes', 'on']:
        return True
    else:
        raise ValueError()


class ConfigureAction(argparse.Action):

    def __init__(self,
                 option_strings,
                 dest,
                 default=None,
                 required=False,
                 help=None,
                 metavar=None,
                 positive_prefixes=['--', '--with-', '--enable-'],
                 negative_prefixes=['--no-', '--without-', '--disable-']):
        strings = []
        self.positive_strings = set()
        self.negative_strings = set()
        for string in option_strings:
            assert re.match(r'--[A-z]+', string)
            suffix = string[2:]
            for positive_prefix in positive_prefixes:
                self.positive_strings.add(positive_prefix + suffix)
                strings.append(positive_prefix + suffix)
            for negative_prefix in negative_prefixes:
                self.negative_strings.add(negative_prefix + suffix)
                strings.append(negative_prefix + suffix)
        super(ConfigureAction, self).__init__(
            option_strings=strings,
            dest=dest,
            nargs='?',
            const=None,
            default=default,
            type=boolean,
            choices=None,
            required=required,
            help=help,
            metavar=metavar)

    def __call__(self, parser, namespace, value, option_string=None):
        if value is None:
            value = option_string in self.positive_strings
        elif option_string in self.negative_strings:
            value = not value
        setattr(namespace, self.dest, value)

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

argparse ConfigureAction problem Neal Becker <ndbecker2@gmail.com> - 2012-03-24 14:30 -0400

csiph-web