Reputation: 415
I am trying to create a simple calculator where it accepts arguments at the command line. For example at the command line:
Calculator.py 1 2 44 6 -add
will give me the sum of the numbers. However, how can the user input infinite amount of arguments. I know you have to use *args or something of the like in functions and i just wanted to know how to incorporate that in the command line using argparse.
Upvotes: 1
Views: 4024
Reputation: 1
import argparse
def operate_numbers(numbers, operation):
return operation(*numbers)
def main():
parser = argparse.ArgumentParser(description="Simple calculator script")
parser.add_argument('numbers', type=int, nargs='+', help='Numbers to operate on')
parser.add_argument('-operation', choices=['add', 'subtract', 'multiply', 'divide'], required=True, help='Operation to perform')
args = parser.parse_args()
operations = {
'add': sum,
'subtract': lambda x: x[0] - sum(x[1:]),
'multiply': lambda x: eval('*'.join(map(str, x))),
'divide': lambda x: eval('/'.join(map(str, x)))
}
result = operate_numbers(args.numbers, operations[args.operation])
print("Result:", result)
if __name__ == "__main__":
main()
Upvotes: 0
Reputation: 5178
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)
https://docs.python.org/3/library/argparse.html
Upvotes: 5
Reputation: 34513
You don't need to, command line arguments are stored in sys.argv
which will give you a list of the command line arguments. You just need to sum over them.
from sys import argv
print sum(map(int, argv[1:])) # We take a slice from 1: because the 0th argument is the script name.
And just do
python testScript.py 1 2 3
6
P.S - Command line arguments are stored as strings, so you need to map
them to integers to sum over them.
*args
is used when you need to pass unknown number of values to a function. Consider the following -
>>> def testFunc(*args):
return sum(args)
>>> testFunc(1, 2, 3, 4, 5, 6)
21
Upvotes: 8