0

I have a single Python file which includes unit tests in the source code. It works like this:

parser = argparse.ArgumentParser()
parser.add_argument('--test', action='store_true', help="Run unit tests and return.")

args = parser.parse_args()

if args.test:
    testsuite = unittest.TestLoader().loadTestsFromTestCase(SanitizeTestCase)
    unittest.TextTestRunner(verbosity=1).run(testsuite)

If args.test is false, the program runs as expected. I don't want to have to make this into an entire setuptools project, it's a pretty simple script with some unit tests to evaluate that it does what it's supposed to.

I now find myself needing to parse other arguments, and that's where things start to fall apart. --test is a mutually exclusive parameter and all of the other parameters don't apply if --test is passed.

Is there a way to have mutually-exclusive argument groups in argparse?

Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411

1 Answers1

0

There is a mutually exclusive group mechanism, but all the arguments in that group are mutually exclusive. You can't say, --test xor any of the other others.

But such a group doesn't do anything profound. It adds some markings to the usage line (try it), and it complains when your user (yourself?) violates the exclusivity.

You can do the same things yourself, and fine tune them. You can give the parser a custom usage line. And after parsing you can choose to ignore conflicting values, or you can choose to raise your own error message (parser.error('dumb user, cant you read ...?')). You could, for example, ignore all the other arguments, regardless of value, if this args.test is True.

hpaulj
  • 221,503
  • 14
  • 230
  • 353