In an attempt to solve this problem from the outside inside - I have an initial implementation that fixes the optparse module, replacing the OptionParser class with a subclass of OptionParser and overloading the parse_args + method, produces a new delayed_parse_args method. I use fragments from this solution if someone else finds it useful or can improve it.
optparse_patch.py
import optparse def patch_opt_parser(): optparse.stashed_parsers = {} class OptionParserEx(optparse.OptionParser): def delayed_parse_args(self, callback): optparse.stashed_parsers[self] = callback def parse_args(self, args=None, values=None): for parser, callback in getattr(optparse,"stashed_parsers").items():
This allows the submodules to βhideβ their expected parameters and have command line parameters evaluated at a later stage, when the module client actually provides OptionParser and calls the parse_args method on its own OptionParser. An example of such a use case is the following:
module.py
import optparse_patch import optparse parser = optparse.OptionParser() group = optparse.OptionGroup(parser, "module options") group.add_option("-f", dest="flip", action="store_true") parser.add_option_group(group) def cli_callback ( opts, args ): if opts.flip: print "flip" opts, args = parser.delayed_parse_args ( cli_callback )
main.py
import module import optparse myparser = optparse.OptionParser() mygroup = optparse.OptionGroup(myparser, "main options") mygroup.add_option("-j", dest="jump", action="store_true") myparser.add_option_group(mygroup) opts, args = myparser.parse_args() if opts.jump: print "jump"
calling main.py program leads to the following outputs:
python main.py --help
Usage: main.py [options] Options: -h, --help show this help message and exit module options: -f main options: -j
python main.py -j -f
flip jump
source share