简体   繁体   English

在python中作为命令行参数传递的数字不会被解释为整数

[英]Numbers passed as command line arguments in python not interpreted as integers

I am familiar with C, and have started experimenting in python. 我熟悉C,并开始在python中进行实验。 My question is regarding the sys.argv command. 我的问题是关于sys.argv命令。 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? 我怎样才能将它们解释为数字?

You can convert the arguments to integers using int() 您可以使用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 输入: 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

Indeed, you have found the problem yourself, sys.argv is an array of strings. 实际上,你自己发现了这个问题, sys.argv是一个字符串数组。

You can transform a string to an integer with int() . 您可以使用int()将字符串转换为整数。 In this case for example: a = int(sys.argv[1]) 例如: a = int(sys.argv[1])

sys.argv items are always strings . sys.argv项始终是strings you should cast them to int with int(a) . 你应该用int(a)将它们转换为int

You can also use third party libraries for handling CLI arguments such as OptParse . 您还可以使用第三方库来处理CLI参数,例如OptParse

In Python, strings are not implicitly converted to integers. 在Python中,字符串不会隐式转换为整数。 Try 尝试

num1 = int(sys.argv[1])
This would represent the numerical value of the number, not its string representation.

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 . 当心包括命令行参数,这可能会导致由于Python 2中的政策比较不同类型的对象真是意外的行为(“诠释” <“名单” <“串” <“元组”)作为指出进行比较的这里 In Python 3, comparing objects of different types will lead to a TypeError. 在Python 3中,比较不同类型的对象将导致TypeError。

For an example of object comparison mayhem, try removing the int() call in section 6.1.1. 有关对象比较混乱的示例,请尝试删除第6.1.1节中的int()调用。 of the Python tutorial Fibonacci code and you'll get an infinite loop, since the while loop condition becomes: 'int' < 'string'. Python教程Fibonacci代码 ,你会得到一个无限循环,因为while循环条件变为:'int'<'string'。 (This would not happen in Perl, btw). (这不会发生在Perl,顺便说一句)。

Great advice from @Jan-Philip above to validate command-line arguments, even for Python 3. 来自@ Jan-Philip的很好的建议来验证命令行参数,即使对于Python 3也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM