Triggering callback on default value in optparse

自闭症网瘾萝莉.ら 提交于 2019-12-12 05:17:24

问题


I'm using Python's optparse to do what it does best, but I can't figure out how to make the option callback trigger on the default argument value if no other is specified via command-line; is this even possible? This would make my code much cleaner.

I can't use argparse unfortunately, as the platform I'm running on has an outdated Python version.

Edit: To provide more detail, I'm adding an option with a callback and a default value

parser.add_option(
  "-f",
  "--format",
  type = "string",
  action = "callback",
  callback = format_callback,
  default = "a,b,c,d")

The callback function is defined as follows:

def format_callback(option, opt, value, parser):
  # some processing
  parser.values.V = processed_value

Basically I'm processing the "--format" value and putting the result into the parser. This works fine, when "--format" is specified directly via command-line, but I'd like the callback to be triggered on the default "a,b,c,d" value as well.


回答1:


It is simply not possible.

The optparse.OptionParser implementation of parse_args starts with:

def parse_args(self, args=None, values=None):
    """
    parse_args(args : [string] = sys.argv[1:],
               values : Values = None)
    -> (values : Values, args : [string])

    Parse the command-line options found in 'args' (default:
    sys.argv[1:]).  Any errors result in a call to 'error()', which
    by default prints the usage message to stderr and calls
    sys.exit() with an error message.  On success returns a pair
    (values, args) where 'values' is an Values instance (with all
    your option values) and 'args' is the list of arguments left
    over after parsing options.
    """
    rargs = self._get_args(args)
    if values is None:
        values = self.get_default_values()

Default values are set before processing any arguments. Actual values then overwrite defaults as options are parsed; the option callbacks are called when a corresponding argument is found.

So callbacks simply cannot be invoked for defaults. The design of the optparse module makes this very hard to change.



来源:https://stackoverflow.com/questions/14568141/triggering-callback-on-default-value-in-optparse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!