You can convert the arguments to integers using int()
import sys
a = int(sys.argv[1]) b = int(sys.argv[2])
print a, b
print a+b
input: python mySum.py 100 200
output:
100 200
300
Answer from Wesley on Stack OverflowYou can convert the arguments to integers using int()
import sys
a = int(sys.argv[1]) b = int(sys.argv[2])
print a, b
print a+b
input: python mySum.py 100 200
output:
100 200
300
You also should validate the user input:
import sys
def is_intstring(s):
try:
int(s)
return True
except ValueError:
return False
for arg in sys.argv[1:]:
if not is_intstring(arg):
sys.exit("All arguments must be integers. Exit.")
numbers = [int(arg) for arg in sys.argv[1:]]
sum = sum(numbers)
print "The sum of arguments is %s" % sum
python - How do I access command line arguments? - Stack Overflow
string - How to read integer command line arguments in Python? - Stack Overflow
python - Run script with integer arguments - Stack Overflow
python - Accept command line arguments as numbers - Stack Overflow
Python tutorial explains it:
import sys
print(sys.argv)
More specifically, if you run python example.py one two three:
>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
I highly recommend argparse which comes with Python 2.7 and later.
The argparse module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv approach. And it is for free (built-in).
Here a small example:
import argparse
parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)
and the output for python prog.py -h
usage: simple_example [-h] counter
positional arguments:
counter counter will be increased by 1 and printed.
optional arguments:
-h, --help show this help message and exit
and the output for python prog.py 1 As one would expect:
2
Python sys.argv always contains the filename as the first argument:
>>> python test.py 1 2 3
>>> sys.argv
['test.py', '1', '2', '3']
If you want to convert it to int, you can do:
nums = map(int, sys.argv[1:])
>>> nums
[1,2,3]
You need to skip sys.argv[0], which is the script's name:
for i in sys.argv[1:]:
# ...
Convert your arguments to integers.
import sys
value1, value2 = (int(x) for x in sys.argv[1:])
This of course assumes that your are expecting exactly two arguments which can be converted to integers.
If you ever want to pass an arbitrary number of integers, you can get a list of them with
argnums = [int(x) for x in sys.argv[1:]]
Also, if you ever plan to write a serious command line interface, consider using argparse.
Everything on argv are strings. You need to manually convert them as integers, like:
value1 = int(argv[1])
value2 = int(argv[2])