Is there a way to add an already created parser as a subparser in argparse?

argparse, command-line-arguments, python

Solution

You could use the `parents` parameter

p=argparse.ArgumentParser()
s=p.add_subparsers()
ss=s.add_parser('script',parents=[initparser()],add_help=False)
p.parse_args('script --foo sst'.split())

`ss` is a parser that shares all the arguments defined for `initparser`. The `add_help=False` is needed on either `ss` or `initparser` so `-h` is not defined twice.

Problem

Normally, to add a subparser in `argparse` you have to do: ``` parser = ArgumentParser() subparsers = parser.add_subparser() subparser = subparsers.add_parser() ``` The problem I'm having is I'm trying to add another command line script, with its own parser, as a subcommand of my main script. Is there an easy way to do this? EDIT: To clarify, I have a file `script.py` that looks something like this: ``` def initparser(): parser = argparse.ArgumentParser() parser.add_argument('--foo') parser.add_argument('--bar') return parser def func(args): #args is a Namespace, this function does stuff with it if __name__ == '__main__': initparser().parse_args() ``` So I can run this like: ``` python script.py --foo --bar ``` I'm trying to write a module `app.py` that's a command line interface with several subcommands, so i can run something like: ``` python app.py script --foo --bar ``` Rather than copy and pasting all of the `initparser()` logic over to `app.py`, I'd like to be able to directly use the parser i create from initparser() as a sub-parser. Is this possible?

Original source