How to declare an optional argument to the parser which disables compulsory argument?

64 views Asked by At

The title may be confusing but I can't think of a better explanation. Basically, I have a program which operates on some input file with a bunch of optional arguments. The input file is compulsory for my program. So I wrote a parser like this:

test.py

from argparse import ArgumentParser

parser = ArgumentParser(prog="prog")
parser.add_argument("file", help="input file")
parser.add_argument("--debug", action="store_true", help="enable debug messages")
parser.parse_args()

I'm not showing all the options for simplicity. Now, I want to add a feature to this program which don't require input file and runs on its own. Let's call this option as a. Option a takes unknown number of arguments and --debug or other options are not valid for option a. So the following would be valid runs for my program:

$ python3 test.py input.txt
$ python3 test.py input.txt --debug
$ python3 test.py -a 1 2 3 

And these would be invalid:

$ python3 test.py input.txt -a 1 2 3 
$ python3 test.py -a 1 2 3 --debug

When I add this line to my code

parser.add_argument("-a", nargs="+", help="help option a")

It accepts option a but it says "file is required" for understandable reasons. So how should I modify my code to achieve my goal?

P.S: I also tried using subparser but I couldn't manage to make it work as I want probably because my lack of knowledge.

0

There are 0 answers