English 中文(简体)
我怎么能选择少选的办法,忽视无效选择?
原标题:How can I get optparse s OptionParser to ignore invalid options?

http://docs.python.org/library/optparse.html#optparse.OptionParser"rel=“nofollow noreferer”>OptionParser ,我如何指示它无视向方法<>提供的不明确的选择?

e.g.
I ve only defined option --foo for my OptionParser instance, but I call parse_args with list: [ --foo , --bar ]

如果把他们从原来的名单上删除,我不小心。 我只想忽略不明确的选择。

这样做的原因是,使用SConsAddOption的Im 接口,以添加习俗,从而形成备选办法。 然而,其中一些选择指导了目标的宣布。 因此,我需要将其从<条码>中删除。 最终,顶级扫描码将涵盖指挥线中所有未界定的选择。

最佳回答

在不同的答复中,我要求把自己的解决办法放在黑板上,在把投入传给母子(<代码>)之前将投入注入活力。 备选案文Parser:

import optparse
import re
import copy
import SCons

class NoErrOptionParser(optparse.OptionParser):
    def __init__(self,*args,**kwargs):
        self.valid_args_cre_list = []
        optparse.OptionParser.__init__(self, *args, **kwargs)

    def error(self,msg):
        pass

    def add_option(self,*args,**kwargs):
        self.valid_args_cre_list.append(re.compile( ^ +args[0]+ = ))
        optparse.OptionParser.add_option(self, *args, **kwargs)

    def parse_args(self,*args,**kwargs):
        # filter out invalid options
        args_to_parse = args[0]
        new_args_to_parse = []
        for a in args_to_parse:
            for cre in self.valid_args_cre_list:
                if cre.match(a):
                    new_args_to_parse.append(a)


        # nuke old values and insert the new
        while len(args_to_parse) > 0:
            args_to_parse.pop()
        for a in new_args_to_parse:
            args_to_parse.append(a)

        return optparse.OptionParser.parse_args(self,*args,**kwargs)


def AddOption_and_get_NoErrOptionParser( *args, **kwargs):
    apply( SCons.Script.AddOption, args, kwargs)
    no_err_optparser = NoErrOptionParser(optparse.SUPPRESS_USAGE)
    apply(no_err_optparser.add_option, args, kwargs)

    return no_err_optpars
问题回答

此处的一条办法是,在结果<代码>/args上添加不为人知的论点,并加上一个简单的子流。

from optparse import (OptionParser,BadOptionError,AmbiguousOptionError)

class PassThroughOptionParser(OptionParser):
    """
    An unknown option pass-through implementation of OptionParser.

    When unknown arguments are encountered, bundle with largs and try again,
    until rargs is depleted.  

    sys.exit(status) will still be called if a known argument is passed
    incorrectly (e.g. missing arguments or bad argument types, etc.)        
    """
    def _process_args(self, largs, rargs, values):
        while rargs:
            try:
                OptionParser._process_args(self,largs,rargs,values)
            except (BadOptionError,AmbiguousOptionError), e:
                largs.append(e.opt_str)

这里还有一刀 to,显示它行之有效:

# Show that the pass-through option parser works.
if __name__ == "__main__": #pragma: no cover
    parser = PassThroughOptionParser()
    parser.add_option( -k ,  --known-arg ,dest= known_arg ,nargs=1, type= int )
    (options,args) = parser.parse_args([ --shazbot , --known-arg=1 ])    
    assert args[0] ==  --shazbot 
    assert options.known_arg == 1

    (options,args) = parser.parse_args([ --k , 4 , --batman-and-robin ])
    assert args[0] ==  --batman-and-robin 
    assert options.known_arg == 4

缺席,便无法修改在通过未经界定的备选办法时提出的“error(”要求的行为。 http://docs.python.org/library/optparse.html#how-optparse-handles-errors” rel=“noreferer” 。

If optparse‘s default error-handling behaviour does not suit your needs, you’ll need to subclass OptionParser and override its exit() and/or error() methods.

最简单的例子是:

class MyOptionParser(OptionParser):
    def error(self, msg):
        pass

这样做只会使所有打到<代码>error()的电话都没有。 当然,这只是一个理想,但我认为,这表明你需要做些什么。 铭记error(> 的指示,在你进行工作时,你应当:

Print a usage message incorporating msg to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception.

页: 1 模块。 您可使用ArgumentParser.parse_ known_args(,以实现这一目标。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签