如何获得optparse的OptionParser忽略无效选项? [英] How can I get optparse's OptionParser to ignore invalid options?

查看:257
本文介绍了如何获得optparse的OptionParser忽略无效选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python的 OptionParser 中,我可以指示它忽略提供给方法 parse_args 的未定义选项吗?

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

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

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


我不在乎是否将其从原始列表中过滤掉.我只想忽略未定义的选项.


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

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

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.

推荐答案

每个synack的请求都在不同的答案注释中,我发布了一个解决方案的技巧,该解决方案在将输入传递给父级OptionParser之前将其净化./p>

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:

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

这篇关于如何获得optparse的OptionParser忽略无效选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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