Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重写OptionParser';python中的s add_选项函数_Python_Optparse - Fatal编程技术网

重写OptionParser';python中的s add_选项函数

重写OptionParser';python中的s add_选项函数,python,optparse,Python,Optparse,我在optpass中为Option和OptionParser编写了一个子类。我正在覆盖OptionParser中的add\u选项函数,使其能够解析新关键字。下面是我的代码 from optparse import Option, OptionError, OptionParser class MyOptionParser(OptionParser): def add_option(self,*args,**kwargs): ##add the new keyword "deft

我在optpass中为
Option
OptionParser
编写了一个子类。我正在覆盖OptionParser中的
add\u选项
函数,使其能够解析新关键字。下面是我的代码

from optparse import Option, OptionError, OptionParser

class MyOptionParser(OptionParser):
    def add_option(self,*args,**kwargs):
    ##add the new keyword "deft". If deft="some value", kwargs[default] = deft
    ##else process args to get deft
        if kwargs.has_key["deft"]:
            newDef = kwargs["deft"]
            del kwargs["deft"]
        else:
            newDef = process_args_for_deft(args)
        if newDef!= None
            kwargs["default"] = newDef
        modOpt = OptionParser.add_option(self,*args,**kwargs)

class MyOption(Option):
    def _set_opt_strings(self, largs, rargs, values):
        #overridden method over here 
现在如果我这样做,效果很好

parser = MyOptionParser()
parser.add_option("-f", "--file", dest="filename",
                 help="write report to FILE", metavar="FILE", deft ="xyz")
但是如果我这样做(我想这样做),它会给我一个错误:MyOption实例没有属性“getitem”,如果没有指定def,并且如果指定了
def
,它会给我一个错误,说没有像
def
这样的类型

parser = MyOptionParser()
parser.add_option(MyOption("-f", "--file", dest="filename",
                 help="write report to FILE", metavar="FILE", def ="xyz"))

我认为问题在于,当我使用MyOption(opts,args)时,我正在传递一个对象,因此它无法访问args/kwargs。我该如何避开这个问题

add\u option
基本上直接调用
option\u类的构造函数(这是默认为
OptionParser.option
OptionParser构造函数的默认参数)

因此,您可能应该只覆盖
MyOption.\uuu init\uuu
(而不覆盖
OptionParser.add\u option
):

如果您希望能够支持以下语法:

parser.add_option("-f", "--file", dest="filename",
             help="write report to FILE", metavar="FILE", deft ="xyz")
然后确保在创建
选项解析器时设置
选项\u class

parser = MyOptionParser(option_class=MyOption)

请发布回溯、
process\u args\u以获取\u def
MyOption.\u set\u opt\u strings
code。另外,
def
是一个保留字,不能用作显式参数名。您可以发布完整的回溯吗?此外,命名变量
def
应该是不可能的,因为它是一个关键字:这到底是如何运行的?我为def
添加了
进程参数,\u选项。\u设置\u选项\u字符串
和回溯。我有一个庞大的代码库,我只想在这里给出代码的相关部分。此外,我还更改了kewword名称,并将其键入为def而不是deft。换了。谢谢
parser = MyOptionParser(option_class=MyOption)