本文介绍了在python中重写OptionParser的add_option函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在optparse中编写了OptionOptionParser的子类.我重写OptionParser中的add_option函数,使其解析新的关键字.以下是我的代码.

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")

但是,如果执行此操作(我想要这样做),则会给我一个错误:如果未指定def并且指定了def,则MyOption实例将没有属性' getitem '错误,提示没有类似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_option基本上直接调用option_class的构造函数(这是OptionParser构造函数的默认参数,默认为optparse.Option)./p>

因此,您可能应该改写MyOption.__init__(而不改写OptionParser.add_option):

class MyOption(Option):
    def __init__(self, *args, **kwargs):
        if 'deft' in kwargs:
            newDef = kwargs.pop('deft')
        else:
            newDef = process_args_for_deft(args)
        if newDef is not None:
            kwargs["default"] = newDef

        Option.__init__(self, *args, **kwargs)

如果您希望能够支持

之类的语法

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

然后只需确保在制作OptionParser时设置option_class:

parser = MyOptionParser(option_class=MyOption)

I have written a subclass for Option and OptionParser in optparse. I am overriding the add_option function in OptionParser to make it parse a new keyword. Following is my code.

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

Now if I do this, it works fine.

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

But if I do this (which I want to) it gives me an error: MyOption instance has no attribute 'getitem' if def is not specified and if def is specified it gives me an error saying no type like def.

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

I think the problem is that I am passing an object when I use MyOption (opts,args) and hence it is not able to access the args/kwargs. How do I get around this problem?

解决方案

add_option basically directly calls the constructor for option_class (which is a default argument to the OptionParser constructor that defaults to optparse.Option).

So, you should probably just override MyOption.__init__ instead (without overriding OptionParser.add_option):

class MyOption(Option):
    def __init__(self, *args, **kwargs):
        if 'deft' in kwargs:
            newDef = kwargs.pop('deft')
        else:
            newDef = process_args_for_deft(args)
        if newDef is not None:
            kwargs["default"] = newDef

        Option.__init__(self, *args, **kwargs)

If you want to be able to support syntax like

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

then just make sure to set option_class when making your OptionParser:

parser = MyOptionParser(option_class=MyOption)

这篇关于在python中重写OptionParser的add_option函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 22:29