Issue
I wrote cmd line interface to perform calculation on a number. If I enter using powershell the command:
python .\regex1.py *x 5 *y 6 *o mul
it prints:
In calc args
Something went wrong
However if i comment out Nargs it gives the expected results.
entered thiscommand: python .\regex1.py *x 5 *y 6 *o mul
Got :mul
30.0
Why is it so, why is Nargs creating this problem and how to solve it while keeping Nargs in our code? The code is below:
import argparse
import sys
def calc(args):
print("In calc args")
if str(args.o) == 'add':
return args.x + args.y
elif str(args.o) == 'mul':
return args.x * args.y
elif str(args.o) == 'sub':
return args.x - args.y
elif str(args.o) == 'div':
return args.x / args.y
else:
return "Something went wrong"
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog= "utility Calculator",
usage= "To perform calculation on an integer",
description="Thsi is arguments help",
epilog="Hope your problem is resolved, if not contact me",
prefix_chars="*",
argument_default= 1.0,
add_help= True,
allow_abbrev= True
)
parser.add_argument('*x',
type=float,
action="store",
nargs=1,
help="Enter first number. This is a utility for calculation. Please contact me",
metavar= " First Number"
)
parser.add_argument('*y',
type=float,
action="store",
nargs=1,
help="Enter Second number. This is a utility for calculation. Please contact me",
metavar= " Second Number"
)
parser.add_argument('*o',
type=str,
# action="store"
nargs=1,
default= "add",
help="Enter the operand."
"*mul for multiplication"
"*add for addition"
"*div for division"
"*sub for subtraction",
metavar= " Operand"
)
args = parser.parse_args()
print(str(args.o), args.x, args.y)
sys.stdout.write(str(calc(args)))
Solution
nargs
serves a different purpose and I'm not sure why you are trying to use it here since your arguments contain only one value.
When nargs=1
your argument is actually a list of that single argument. If you remove the nargs=1
you get the argument itself. And looking at your code, all if
statements fail and that's why you get Something went wrong
.
Referencing the documentation where you can learn more about nargs
:
N
(an integer). N
arguments from the command line will be gathered together into a list. For example:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])
Note that nargs=1
produces a list of one item. This is different from the default, in which the item is produced by itself.
Answered By - Vlad Siv
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.