此处的一条办法是,在结果<代码>/args上添加不为人知的论点,并加上一个简单的子流。
from optparse import (OptionParser,BadOptionError,AmbiguousOptionError)
class PassThroughOptionParser(OptionParser):
"""
An unknown option pass-through implementation of OptionParser.
When unknown arguments are encountered, bundle with largs and try again,
until rargs is depleted.
sys.exit(status) will still be called if a known argument is passed
incorrectly (e.g. missing arguments or bad argument types, etc.)
"""
def _process_args(self, largs, rargs, values):
while rargs:
try:
OptionParser._process_args(self,largs,rargs,values)
except (BadOptionError,AmbiguousOptionError), e:
largs.append(e.opt_str)
这里还有一刀 to,显示它行之有效:
# Show that the pass-through option parser works.
if __name__ == "__main__": #pragma: no cover
parser = PassThroughOptionParser()
parser.add_option( -k , --known-arg ,dest= known_arg ,nargs=1, type= int )
(options,args) = parser.parse_args([ --shazbot , --known-arg=1 ])
assert args[0] == --shazbot
assert options.known_arg == 1
(options,args) = parser.parse_args([ --k , 4 , --batman-and-robin ])
assert args[0] == --batman-and-robin
assert options.known_arg == 4