user3467349
user3467349

Reputation: 3191

Python Argsparser add a single argument to subparser without a name

There is extensive documentation for how to do a bunch of complex things, whereas I can't seem to find something very simple - I have a script with some actions:

subparsers = parser.add_subparsers(dest='action', help='do this')
parser_act_one = subparsers.add_parser('actone')
parser_act_one.add_argument('--function', type=str)
parser_act_two = subparsers.add_parser('acttwo')
parser_act_two.add_argument('--function', type=str)

Since they only take one argument a piece I would like to do the equivalent of parser_enmod.add_argument() without a name which doesn't seem to work.

Edit: To clarify: What I would like to run is:

python my_script.py actone 'special_name' 

instead of:

python my_script.py actone --function='special_name'

Upvotes: 1

Views: 672

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122132

You still need to name your positional arguments, but you simply don't start them with the -- prefix to make them positional instead:

subparsers = parser.add_subparsers(dest='action', help='do this')
parser_act_one = subparsers.add_parser('actone')
parser_act_one.add_argument('function', type=str)
parser_act_two = subparsers.add_parser('acttwo')
parser_act_two.add_argument('function', type=str)

Demo:

>>> import argparse
>>> parser = argparse.ArgumentParser(description='Demo')
>>> subparsers = parser.add_subparsers(dest='action', help='do this')
>>> parser_act_one = subparsers.add_parser('actone')
>>> parser_act_one.add_argument('function', type=str)
_StoreAction(option_strings=[], dest='function', nargs=None, const=None, default=None, type=<type 'str'>, choices=None, help=None, metavar=None)
>>> parser_act_two = subparsers.add_parser('acttwo')
>>> parser_act_two.add_argument('function', type=str)
_StoreAction(option_strings=[], dest='function', nargs=None, const=None, default=None, type=<type 'str'>, choices=None, help=None, metavar=None)
>>> parser.print_help()
usage: [-h] {actone,acttwo} ...

Demo

positional arguments:
  {actone,acttwo}  do this

optional arguments:
  -h, --help       show this help message and exit
>>> parser_act_one.print_help()
usage:  actone [-h] function

positional arguments:
  function

optional arguments:
  -h, --help  show this help message and exit
>>> parser.parse_args(['actone', 'some_filename.txt'])
Namespace(action='actone', function='some_filename.txt')

Upvotes: 2

Related Questions