Numbers passed as command line arguments in python not interpreted as integers
Asked Answered
A

6

34

I am familiar with C, and have started experimenting in python. My question is regarding the sys.argv command. I've read it is used for a command line interpreter, but when trying to execute a simple program I don't get the results I expect.

Code:

import sys

a = sys.argv[1]
b = sys.argv[2]

print a, b

print a+b

Input:

python mySum.py 100 200

Output:

100 200
100200

When I add the two arguments they are concatenated instead of the two values being added together. It seems that the values are being taken as strings.

How can I interpret them as numerics?

Avaricious answered 25/5, 2012 at 9:34 Comment(2)
A similar problem would occur in C: arguments are passed to main() as strings, and you would need to use sscanf() or atoi() to convert them to integers.Pratt
This is a very vague title. Can someone edit it to accurately describe the question?Kernel
S
46

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
Sublimate answered 25/5, 2012 at 9:36 Comment(0)
P
16

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
Pantheon answered 25/5, 2012 at 12:46 Comment(1)
I was about to write a new answer that says one should validate it before using int(), before I saw your answer! One can also use isdigit() that returns TRUE if all the characters in the string are (0-9).Rawson
C
14

Indeed, you have found the problem yourself, sys.argv is an array of strings.

You can transform a string to an integer with int(). In this case for example: a = int(sys.argv[1])

Chukchi answered 25/5, 2012 at 9:36 Comment(0)
E
5

sys.argv items are always strings. you should cast them to int with int(a).

You can also use third party libraries for handling CLI arguments such as OptParse.

Edema answered 25/5, 2012 at 9:37 Comment(0)
D
1

In Python, strings are not implicitly converted to integers. Try

num1 = int(sys.argv[1])
This would represent the numerical value of the number, not its string representation.
Diandiana answered 17/10, 2014 at 1:24 Comment(0)
H
0

Beware of performing comparisons involving command-line arguments, which can lead to really unexpected behavior owing to Python 2's policy for comparing objects of different types ('int' < 'list' < 'string' < 'tuple') as noted here. In Python 3, comparing objects of different types will lead to a TypeError.

For an example of object comparison mayhem, try removing the int() call in section 6.1.1. of the Python tutorial Fibonacci code and you'll get an infinite loop, since the while loop condition becomes: 'int' < 'string'. (This would not happen in Perl, btw).

Great advice from @Jan-Philip above to validate command-line arguments, even for Python 3.

Hypertonic answered 6/7, 2017 at 23:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.