Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: "unrecognized arguments"

Tags:

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.

like image 267
Zvonimir Peran Avatar asked Jul 17 '15 06:07

Zvonimir Peran


People also ask

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What is ArgumentParser in Python?

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.

What is Argparse ArgumentParser ()?

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.


1 Answers

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

like image 72
Rakholiya Jenish Avatar answered Sep 18 '22 19:09

Rakholiya Jenish