I’m making a pretty simple script which takes the following parameters:
-p --port integer, optional, default 5050
-f --fork boolean, optional, default False
action string, required, needs to be either start or stop
I’ve tried implementing this in argparse, but it’s not printing help when action string isn’t provided, it’s just failing all ugly-like:
usage: __init__.py [-h] [-p PORT] [-f] {start,stop}
__init__.py: error: argument action: invalid choice: '__init__.py' (choose from 'start', 'stop')
Even when I pass “start” or “stop”, it fails with the same message. Here’s my code:
parser = argparse.ArgumentParser(description="Start or stop the server.",
epilog="If you don't know what you're doing, run. Run for your life.\n")
parser.add_argument("-p", "--port", type=int, nargs=1, default=5050,
dest="port", help="The port to run the server on.")
parser.add_argument("-f", "--fork", action="store_true", default=False,
dest="fork", help="Fork to background? Default is false.")
parser.add_argument("action", type=str, choices=("start","stop"), help="Whether to 'start' or 'stop' the server.")
What am I doing wrong here? Hopefully my intentions are pretty clear from my code.
What version of Python are you using? When I run your code with 2.7.1 it works fine.
One tip, if you specify ‘prog’ in the ctor you can override it using init.py as the filename
Also, it is printing usage, but not the long help.. You could do something like this to make things a little more obvious..