I'm working on a simple Git/Redmine glue script but I'm having some difficulty using optional arguments with the Python argparse
module.
With the following code:
import argparse
class MyClass:
def StartWork(self, issueNumber, **kwargs):
if issueNumber is None:
issueNumber = input("please enter an issue number: ")
else:
print("issue number detected")
print(issueNumber)
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='MyClass-command', help='Command to perform')
subparsers.required = True
startWorkParser = subparsers.add_parser('startwork', help='Command to begin work on a new branch')
startWorkParser.add_argument("issuenumber", type=int, help="The issue number used to create a local branch based on the specified issue number", nargs='?', default=None)
startWorkParser.set_defaults(func=MyClass.StartWork)
# Parse the arguments to make sure we have all the information requried to actually do something.
args = parser.parse_args()
mc = MyClass()
try:
args.func(mc, **vars(args))
except AssertionError as e:
print("Error: "+str(e))
# Parse the arguments to make sure we have all the information required to actually do something.
args = parser.parse_args()
I'd expect a call like this:
python MyClass.py startwork
...to result in the user being prompted for an issue number. Instead I get:
Traceback (most recent call last):
File "C:\Projects\RedmnieGlue\MyClass.py", line 23, in <module>
args.func(mc, **vars(args))
TypeError: StartWork() missing 1 required positional argument: 'issueNumber'
So why is the nargs='?'
not prevailing here?
Edit
If I call it like this:
python MyClass.py startwork -h
I get this:
usage: class1.py startwork [-h] [issuenumber]
positional arguments:
issuenumber The issue number used to create a local branch based on the
specified issue number
optional arguments:
-h, --help show this help message and exit
...which (based on the []
around issuenumber
) suggests to me it is understanding that is an optional argument but something is preventing it from working as I'd expect it to. Something to do with my use of subparsers
and calling methods with the arg parser perhaps?