python 如何让 optparse 的 OptionParser 忽略无效选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1885161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:17:01  来源:igfitidea点击:

How can I get optparse's OptionParser to ignore invalid options?

pythonoptparse

提问by Ross Rogers

In python's OptionParser, how can I instruct it to ignore undefined options supplied to method parse_args?

在 python 中OptionParser,如何指示它忽略提供给方法的未定义选项parse_args

e.g.
I've only defined option --foofor my OptionParserinstance, but I call parse_argswith list
[ '--foo', '--bar' ]

例如,
我只--foo为我的OptionParser实例定义了选项,但我parse_args用列表调用
[ '--foo', '--bar' ]

EDIT:
I don't care if it filters them out of the original list. I just want undefined options ignored.

编辑:
我不在乎它是否将它们从原始列表中过滤掉。我只想忽略未定义的选项。

The reason I'm doing this is because I'm using SCons' AddOption interface to add custom build options. However, some of those options guide the declaration of the targets. Thus I need to parse them out of sys.argv at different points in the script without having access to all the options. In the end, the top level Scons OptionParser will catch all the undefined options in the command line.

我这样做的原因是因为我使用 SCons 的 AddOption 接口来添加自定义构建选项。但是,其中一些选项指导目标的声明。因此,我需要在脚本的不同点从 sys.argv 解析它们,而无需访问所有选项。最后,顶级 Scons OptionParser 将捕获命令行中所有未定义的选项。

采纳答案by Ross Rogers

Per synack's request in a different answer's comments, I'm posting my hack of a solution which sanitizes the inputs before passing them to the parent OptionParser:

根据 Synack 在不同答案的评论中的请求,我发布了一个解决方案的 hack,该解决方案在将输入传递给父级之前对其进行消毒OptionParser

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

回答by justind

Here's one way to have unknown arguments added to the result argsof OptionParser.parse_args, with a simple subclass.

这里有一个方法,有添加到结果未知参数argsOptionParser.parse_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)

And here's a snippet to show that it works:

这是一个片段来表明它有效:

# 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

回答by jathanism

By default there is no way to modify the behavior of the call to error()that is raised when an undefined option is passed. From the documentation at the bottom of the section on how optparse handles errors:

默认情况下,无法修改error()传递未定义选项时引发的调用行为。从有关optparse 如何处理错误的部分底部的文档中:

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.

如果 optparse 的默认错误处理行为不适合您的需要,您需要子类化 OptionParser 并覆盖其 exit() 和/或 error() 方法。

The simplest example of this would be:

最简单的例子是:

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

This would simply make all calls to error()do nothing. Of course this isn't ideal, but I believe that this illustrates what you'd need to do. Keep in mind the docstring from error()and you should be good to go as you proceed:

这只会使所有调用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.

将包含 'msg' 的使用消息打印到 stderr 并退出。如果您在子类中覆盖它,它不应该返回——它应该退出或引发异常。

回答by Tim Ruddick

Python 2.7 (which didn't exist when this question was asked) now provides the argparsemodule. You may be able to use ArgumentParser.parse_known_args()to accomplish the goal of this question.

Python 2.7(提出这个问题时不存在)现在提供了argparse模块。你或许可以使用ArgumentParser.parse_known_args()来完成这个问题的目标。

回答by anatoly techtonik

This is pass_through.pyexample from Optik distribution.

这是pass_through.py来自Optik 发行版的示例。

#!/usr/bin/env python

# "Pass-through" option parsing -- an OptionParser that ignores
# unknown options and lets them pile up in the leftover argument
# list.  Useful for programs that pass unknown options through
# to a sub-program.

from optparse import OptionParser, BadOptionError

class PassThroughOptionParser(OptionParser):

    def _process_long_opt(self, rargs, values):
        try:
            OptionParser._process_long_opt(self, rargs, values)
        except BadOptionError, err:
            self.largs.append(err.opt_str)

    def _process_short_opts(self, rargs, values):
        try:
            OptionParser._process_short_opts(self, rargs, values)
        except BadOptionError, err:
            self.largs.append(err.opt_str)


def main():
    parser = PassThroughOptionParser()
    parser.add_option("-a", help="some option")
    parser.add_option("-b", help="some other option")
    parser.add_option("--other", action='store_true',
                      help="long option that takes no arg")
    parser.add_option("--value",
                      help="long option that takes an arg")
    (options, args) = parser.parse_args()
    print "options:", options
    print "args:", args

main()