11

I'm experimenting with argparse, the program works, but default values don't work. Here's my code:

'''This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.'''

import argparse
import sys

def calc(args):
    #Enable variables within the function to take on values from 'args' object. 
    operation = args.operation
    x = args.x
    y = args.y

    if (operation == "add"):
        return x + y
    elif (operation == "sub"):
        return x - y

parser = argparse.ArgumentParser(description="This is a summing program")   #parser is an object of the class Argument Parser.
parser.add_argument("x", type=float, default=1.0, help="What is the first number?") #add_argument is a method of the class ArgumentParser.
parser.add_argument("y", type=float, default=1.0, help='What is the second number?')
parser.add_argument("operation", type=str, default="add", help='What operation? Can choose add, sub, mul, or div')
args = parser.parse_args()
print(str(calc(args)))

This simple program work, however attempting to call it without values returns the following error:

usage: cmdline.py [-h] x y operation
cmdline.py: error: the following arguments are required: x, y, operation

Where am I going wrong?

2
  • 1
    You're using positional, not keyword, arguments without appropriate nargs. Read docs.python.org/3/library/argparse.html#default. Commented May 18, 2018 at 11:21
  • I can reproduce the issue you see. You could use 'mode' for 'operation', not that it will solve the problem posed. Commented May 18, 2018 at 11:35

3 Answers 3

7

You are missing nargs='?'. The following works:

import argparse
import sys 

def calc(args):
    #Enable variables within the function to take on values from 'args' object. 
    operation = args.operation
    x = args.x
    y = args.y

    if (operation == "add"):
        return x + y 
    elif (operation == "sub"):
        return x - y 

parser = argparse.ArgumentParser(description="This is a summing program")   #parser is an object of the class Argument Parser.
parser.add_argument("x", nargs='?', type=float, default=1.0, help="What is the first number?") #add_argument is a method of the class ArgumentParser.
parser.add_argument("y", nargs='?', type=float, default=1.0, help='What is the second number?')
parser.add_argument("operation", nargs='?', type=str, default="add", help='What operation? Can choose add, sub, mul, or div')
args = parser.parse_args()
print(str(calc(args)))
Sign up to request clarification or add additional context in comments.

1 Comment

doesn't work for me. Please explain why would it work
5

Change these lines to indicate that you want named, optional command-line arguments (so "-x" not "x"):

parser.add_argument("-x", type=float, default=1.0, help="What is the first number?") #add_argument is a method of the class ArgumentParser.
parser.add_argument("-y", type=float, default=1.0, help='What is the second number?')

5 Comments

Thanks for that - it works! But is there a way that I can use the default values AND use the program easily. i.e. typing python cmdline.py should print out 2.0 and typing cmdline.py 3 4 should print out 7. Basically, I want the cake and eat it too!?
@jbcoe So suppose you have 2 arguments, both with different defaults, and you want to supply only the second argument. How is the program to know that the first argument gets the default value, and not the second?
@BoarGules It won't know. That's a limit which names arguments would get round.
So true! I get it now! Thanks buddy!
@MonkeyBot2020 You can have your cake and eat it too if you use jbcoe's approach. But only if the default values are the same.
1

@jbcoe - I think you have a few typoes in your code, but thank you, it works! Here's the solution, cleaned up:

'''This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument. It uses the argparse module.'''

import argparse

def calc(args):
    #Enable variables within the function to take on values from 'args' object. 
    operation = args.operation
    x = args.x
    y = args.y

    if (operation == "add"):
        return x + y
    elif (operation == "sub"):
        return x - y

parser = argparse.ArgumentParser(description="This is a summing program")   #parser is an object of the class Argument Parser.
parser.add_argument("x", nargs='?', type=float, default=1.0, help="What is the first number?") #add_argument is a method of the class ArgumentParser.
parser.add_argument("y", nargs='?', type=float, default=2.0, help='What is the second number?')
parser.add_argument("operation", nargs='?', type=str, default="add", help='What operation? Can choose add, sub, mul, or div')
args = parser.parse_args()
print(str(calc(args)))

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.