0

I have this three types of commands in code:

test.py save file_name
test.py load file_name
test.py list_files

Currently, to parse them i use three subparsers, but is there opportunity to use one subparser to two commads 'load' and 'save', because they use same argument 'file_name'?

parser = argparse.ArgumentParser(description='Test parser')
subparsers = parser.add_subparsers(dest='command')

parser_load = subparsers.add_parser("load")
parser_load.add_argument("file_name")

parser_save = subparsers.add_parser("save")
parser_save.add_argument("file_name")

parser_list_files = subparsers.add_parser("list_files")
Nucrea
  • 1
  • I've never done this myself, but I found this question after a quick search and it looks promising: [Add argument to multiple subparsers](https://stackoverflow.com/q/7498595/4518341) – wjandrea Mar 26 '21 at 23:09
  • What's wrong with the code you show? You've already done the hard work of typing both cases :) But you could try making `save` an alias for `load`. I think the alias will appear as the `command` value (but check). – hpaulj Mar 26 '21 at 23:14

1 Answers1

0

If the two commands are identical, they can be aliases of the same parser

In [6]: parser = argparse.ArgumentParser()
In [7]: sp = parser.add_subparsers(dest='cmd')
In [8]: sp1 = sp.add_parser('load', aliases=['store'])
In [9]: sp1.add_argument('test');

In [10]: parser.parse_args('load foo'.split())
Out[10]: Namespace(cmd='load', test='foo')

In [12]: parser.parse_args('store foo'.split())
Out[12]: Namespace(cmd='store', test='foo')

The alias appears in the namespace.

In [13]: parser.print_help()
usage: ipython3 [-h] {load,store} ...

positional arguments:
  {load,store}

optional arguments:
  -h, --help    show this help message and exit

But if you prefer to keep them separate, there are various ways to ease your typing burden.

  • There's copy-n-paste
  • There's the parents mechanism, cute but limited.
  • Or use one or more utility functions to create multiple subparsers.

The Perl inventor claimed programmers are lazy, going to great lengths to avoid typing repetitive code. http://threevirtues.com/

hpaulj
  • 221,503
  • 14
  • 230
  • 353