I’m trying to make argparse ignore the fact that two normally required positional arguments shouldn’t be evaluated when an optional argument (-l) is specified.
Basically I’m trying to replicate the behavior of –help: when you specify the -h, all missing required arguments are ignored.
Example code:
parser = argparse.ArgumentParser(description="Foo bar baz")
parser.add_argument('arg1', help='arg1 is a positional argument that does this')
parser.add_argument('arg2', help='arg2 is a positional argument that does this')
parser.add_argument('-l', '--list', dest='list', help='this is an optional argument that prints stuff')
options, args = parser.parse_args()
if options.list:
print "I list stuff"
And of course, if I run it now, I get :
error: too few arguments
I tried different things like nargs='?', but couldn’t get anything working.
This question is quite similar but wasn’t answered.
Unfortunately,
argparseisn’t quite flexible enough for this. The best you can do is to makearg1andarg2optional usingnargs="?"and check yourself whether they are given if needed.The internal
helpaction is implemented by printing the help message and exiting the program as soon as-hor--helpare encountered on the command line. You could write a similar action yourself, something like(Warning: untested code!)
There are definite downsides to the latter approac, though. The help message will unconditionally show
arg1andarg2as compulsory arguments. And parsing the command line simply stops when encountering-lor--list, ignoring any further arguments. This behaviour is quite acceptable for--help, but is less than desirable for other options.