0

I'd like to create an app that either loads a config file or inits a config file. The syntax i would like to achieve:

app /some/path/config.json  # loads config.json

or

app init  # create a config.json with some predefined stuff

The two different positional arguments would have related optional parameters.

I know I can use subparsers to achieve this:

argument = argparse.ArgumentParser()
subparser = argument.add_subparsers()

config_subparser = subparser.add_parser("config")
config_subparser.add_argument(
    'config',
    help='Path to configuration file.',
    nargs='?'
)

init_subparser = subparser.add_parser("init")
init_subparser.add_argument(
    'init',
    help='initializes workspace'
)

But my problem is that this code has to be called with an additional 'config' string:

app config config.json

Is it possible to create a "nameless" positional param so that the 'config' string can be left out from the call?

Thanks in advance! :)

  • Your task will be simpler if you just use a pair of `optionals`, possibly in a mutually_exclusive_group. I think subparsers is overly complicated for your needs. – hpaulj Oct 15 '20 at 15:39
  • This application I'm woring on actually has a lot of optionals that's related to one subparser only. – Attila Molnár Oct 16 '20 at 16:07
  • 1
    Anyways, there isn't a `nameless` subparser mechanism. Subparsers are optional - in fact you have to take extra steps to ensure they aren't (using `required` and `dest` parameters). BUT, beware that the subparser argument is actually a `positional`, and positionals get values by position not value. Experiment with a few simple cases. – hpaulj Oct 16 '20 at 18:56
  • 1
    Maybe this prior answer will help: https://stackoverflow.com/questions/64042616/python-argparse-with-subparsers-and-optional-positional-arguments/64052292#64052292 – hpaulj Oct 16 '20 at 18:57

0 Answers0