I am trying to use my program with command line option. Here is my code:
import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument("-u","--upgrade", help="fully automatized upgrade") args = parser.parse_args() if args.upgrade: print "Starting with upgrade procedure" main()
When I try to run my program from terminal (python script.py -u
), I expect to get the message Starting with upgrade procedure
, but instead I get the error message unrecognized arguments -u
.
Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
argparse — parse the arguments. Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user. That user might be your future self.
The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.
The error you are getting is because -u
is expecting a some value after it. If you use python script.py -h
you will find it in usage statement saying [-u UPGRADE]
.
If you want to use it as boolean or flag (true if -u
is used), add an additional parameter action
:
parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action="store_true")
action
- The basic type of action to be taken when this argument is encountered at the command line
With action="store_true"
, if the option -u
is specified, the value True is assigned to args.upgrade
. Not specifying it implies False.
Source: Python argparse documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With