1

Is there a way to make an argument strictly used alone, without other flags, or it throws an error?

import argparse

parser = argparse.ArgumentParser(description='description')
parser.add_argument("-n", "--line-number", help="print line numbers", action="store_true")
parser.add_argument("-e", "--errors", action="store_true", help="errors")
parser.add_argument("--debug", action="store_true", help="debug")

So for example in the code above, I want --debug to be used alone. If there are any other flags it would throw an error, but the -n and -e flag can still be used together like in the example below.

$ python3 file.py --debug // It works
$ python3 file.py --debug -n -e // Error: --debug can only be used alone...
$ python3 file.py -n -e // Work together
$ python3 file.py -n // or alone

I've tried using groups and reading the documentation but I haven't found anything useful.

How can I implement this behavior?

martineau
  • 119,623
  • 25
  • 170
  • 301
TheRealHou
  • 11
  • 4
  • 2
    Does this answer your question? [Python argparse mutual exclusive group](https://stackoverflow.com/questions/17909294/python-argparse-mutual-exclusive-group) "I've tried using groups and reading the documentation but I haven't found anything useful." Please try searching in that documentation for the part about "mutually exclusive groups". Also, did you know there is a [specific argparse tutorial](https://docs.python.org/3/howto/argparse.html) built right into the documentation? – Karl Knechtel May 26 '22 at 23:49
  • 1
    One option is to just ignore the others. Or test things after parsing and complain. `help` and `version` have `Action` subclasses that "exit". Otherwise, there isn't anything special in `argparse` for this. – hpaulj May 26 '22 at 23:51
  • @KarlKnechtel, a problem with `mutually_exclusive` is that doesn't have any provision for allowing the either-or-or-both of the other arguments. It is a simple flat `xor`. – hpaulj May 26 '22 at 23:52
  • @hpaulj which, from what I can understand from the specification, is *perfectly fine*. One group contains the `debug` option, which must not be used in combination with anything else, per OP's description. the other group contains the `n` and `e` options, which can be used separately or with each other, but not with `debug`. – Karl Knechtel May 26 '22 at 23:53
  • 1
    @KarlKnechtel Based on my quick scan of the docs, `add_mutually_exclusive_group` means that the arguments within the group are mutually exclusive with each other, **not** that the 2 groups are mutually exclusive with each other. Is there something I'm missing? – SuperStormer May 26 '22 at 23:57
  • Right, there are no subgroups in a mutually exclusive group. – hpaulj May 27 '22 at 00:20
  • my answer in the duplicate still stands – hpaulj May 27 '22 at 00:25
  • Sorry, my mistake. – Karl Knechtel May 27 '22 at 00:42

0 Answers0