How Do I Make An Argparse Argument Optional When Using Subparsers?
Solution 1:
If you print the contents of vars(args)
before your function call like this:
print(vars(args))
args.func(mc, **vars(args))
Then you can easily verify whether there is something wrong with the argument parser or not. With a call of the script without arguments (e.g. python myscript.py
), you get the following output:
{'MyClass-command': 'startwork', 'issuenumber': None, 'func': <function MyClass.StartWork at 0x000000493898C510>}
As you can see issuenumber
actually is in that dictionary, and it did get the default value. So the error you are seeing is not because of the argument parser (it’s also not an argparse error, so the validation on the arguments—with issuenumber
being optional—is absolutely correct).
Instead, what’s going wrong is that the argument issuenumber
is not passed to the positional argument when using **vars(args)
. The reason that does not happen is actually quite simply:
The dictionary key is issuenumber
; the function expects a issueNumber
(note the upper case N
). So either change the function to use a lowercase issuenumber
, or change the argument parser to store the value in issueNumber
instead.
Post a Comment for "How Do I Make An Argparse Argument Optional When Using Subparsers?"