Reputation: 711
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
.
Upvotes: 27
Views: 79274
Reputation: 3223
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
Upvotes: 24
Reputation: 631
For Boolean arguments use action="store_true":
parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action="store_true")
See: https://docs.python.org/2/howto/argparse.html#introducing-optional-arguments
Upvotes: 3
Reputation: 90889
Currently, your argument requires a value to be passed in for it as well.
If you want -u
as an option instead, Use the action='store_true'
for arguments that do not need a value.
Example -
parser.add_argument("-u","--upgrade", help="fully automatized upgrade", action='store_true')
Upvotes: 3