Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse default values not working

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?

like image 446
Legion Avatar asked May 18 '18 11:05

Legion


Video Answer


2 Answers

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)))
like image 99
jbcoe Avatar answered Oct 27 '22 00:10

jbcoe


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?')
like image 27
BoarGules Avatar answered Oct 27 '22 00:10

BoarGules