Optocoupler is not responding

I'm trying to find out better optparse, but I'm afraid to understand why the following code behaves the way it does. Am I doing something stupid?

import optparse

def store_test(option, opt_str, value, parser, args=None, kwargs=None):
    print 'opt_str:', opt_str
    print 'value:', value

op = optparse.OptionParser()
op.add_option('-t', '--test', action='callback', callback=store_test, default='test', 
    dest='test', help='test!')

(opts, args) = op.parse_args(['test.py', '-t', 'foo'])

print
print 'opts:'
print opts
print 'args:'
print args

Conclusion:

opt_str: -t
value: None

opts:
{'test': 'test'}
args:
['foo']

Why is it 'foo'not passed in store_test()and is instead interpreted as an additional argument? Is something wrong with op.parse_args(['-t', 'foo'])?

http://codepad.org/vq3cvE13

Edit:

Here is an example from the docs:

def store_value(option, opt_str, value, parser):
    setattr(parser.values, option.dest, value)
[...]
parser.add_option("--foo",
                  action="callback", callback=store_value,
                  type="int", nargs=3, dest="foo")
+5
source share
1 answer

You are missing the "type" or "nargs" attribute :

op.add_option('-t', '--test', action='callback', callback=store_test, default='test',
    dest='test', help='test!', type='str')

This parameter will force it to use the following argument.

: http://docs.python.org/library/optparse.html#optparse-option-callbacks


    : "" "", optparse . , , optparse .

nargs
    : > 1, optparse nargs , . .

, optparse.py:

def takes_value(self):
    return self.type is not None

def _process_short_opts(self, rargs, values):
    [...]
        if option.takes_value():
            # Any characters left in arg?  Pretend they're the
            # next arg, and stop consuming characters of arg.
            if i < len(arg):
                rargs.insert(0, arg[i:])
                stop = True

            nargs = option.nargs
            if len(rargs) < nargs:
                if nargs == 1:
                    self.error(_("%s option requires an argument") % opt)
                else:
                    self.error(_("%s option requires %d arguments")
                               % (opt, nargs))
            elif nargs == 1:
                value = rargs.pop(0)
            else:
                value = tuple(rargs[0:nargs])
                del rargs[0:nargs]

        else:                       # option doesn't take a value
            value = None

        option.process(opt, value, values, self)
+5

All Articles