0

My program has two functionalities. One is run without any arguments, and the other can have optional arguments. The groups can't interfere with each other.

import argparse

parser = argparse.ArgumentParser()

root_group = parser.add_mutually_exclusive_group()

group_export = root_group.add_argument_group()
group_export.add_argument('--export', action='store_true', help='Exports data from database')
group_export.add_argument('-l', action='append', help='Reduce output with league name')
group_export.add_argument('-d', action='append', help='Reduce output with date range')

group_run = root_group.add_argument_group()
group_run.add_argument('--run', action='store_true', help='Start gathering of data')

I want this to be allowed:

python file.py --export -l name1 -l name2 -d 1/1/2015
python file.py --export
python file.py --run

And this to be not allowed:

python file.py --run --export  # Namespace(d=None, export=True, l=None, run=True)

python file.py --run -l name1  # Namespace(d=None, export=False, l=['name1'], run=True)

However, as on now neither of the disallowed operations rises an error, as indicated by the comments.

Bartek R.
  • 441
  • 1
  • 8
  • 15

1 Answers1

1

Argument groups don't nest inside a mutually exclusive group. Despite the names, the two kinds of groups have different purposes.

Argument groups group arguments in the help display. They do nothing during parsing.

Mutually exclusive groups test the occurrence of arguments, and try to display that in the usage line.

You could make --export and --run mutually exclusive. But it won't block the use of l or d with run. But you could just ignore those values. Or you could do your own tests after parsing, and complain that the point.

What would be a meaningful way of representing this constrain in the usage line? You may need to customize that.

Another possibility is to use subparsers. That might fit your case better. The 'export' parser would define the arguments that work with that. The 'run' would not accept any further arguments.

In one way or other this has been discussed in other argparse questions. The sidebar seems to have found some possible matches.

hpaulj
  • 221,503
  • 14
  • 230
  • 353