27

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.

2
  • I am not seeing any error message and I am getting your expecpted output; I think it could be because of space, tab in your program Please verify that [viswesn.viswesn-PC] ➤ python script.py -u 10 Starting with upgrade procedure [viswesn.viswesn-PC] ➤ python script.py -u usage: script.py [-h] [-u UPGRADE] script.py: error: argument -u/--upgrade: expected one argument Commented Jul 17, 2015 at 6:51
  • 2
    The only issue here, is that -u will expect a value or some sort. try doing python myscript.py -u True Commented Jul 17, 2015 at 6:57

3 Answers 3

24

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

Sign up to request clarification or add additional context in comments.

Comments

3

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')

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.