I'm building a set of scripts and modules for some project. By request, there are some required command line arguments. Also some modules can use some custom arguments (like numerical tolerance, or parameters). All the scripts and modules can use another set of common arguments (verbosity level, for example).
I'm trying to use the python3 argparse for that.
|- bin
| +- scriptN.py
|- lib
| +- requested_args.py
| +- common_args.py
| +- dataset.py
| +- modelN.py
I tried to use a nested parent argparser, as:
in scriptN.py:
parser = argparser.ArgumentParser(parents=[requested_args.parser,
commont_args.parser,
dataset.parser,
modelN.parser]
And for the modelN file:
parser = argparser.ArgumentParser(add_help=False,
parents=[requested_args.parser,
commont_args.parser]
So request_args and common_args parsers are "included" twice, resulting that the same option is already defined.
I need to expose in scriptN.py all the options for the imported modules, and each module can access their own args, and the two common modules. For simplicity, each module/script has a "args" object.
I tried to use the approach described in this question, but I can`t figure how to expose the module args within the module. How can I join all argparses, and maintain all the parsedArguments available in each module and for all modules?
Thanks
parentsmechanism simply copies argument (Actionobject) references from the parent to the child. It doesn't actually run the parent parser.conflict_handler='resolve'is another way of handling repeated Action definitions, but it isn't robust. You may need to customize thishandler, or write your own variation on theparentsmechanism.add_argumentcreates anargparse.Actionsubclass object, and stores references to it in several places, including theparser_actionslist. But look atparser._add_container_actionsto see how Actions are actually copied from one parser to another. It isn't trivial.parentsindatasetandmodelNfiles. Only keep onscriptN. I really want to make the parsed arguments available inside the module.parse_known_argsit is possible to use several parsers at once, each handling only the arguments it knows about. A different approach is to have one master parser, and have it pass itsargsvariable to the sub modules. That's an inter-module variable issue, not anargparseone.