简而言之:
在Python 2.7中,input
函数会将你输入的任何内容作为Python表达式进行评估。如果你只想读取字符串,则使用raw_input
函数,它不会评估所读取的字符串。
如果你正在使用Python 3.x,则raw_input
已经更名为input
函数。引用Python 3.0发布说明,
raw_input()
被重命名为input()
。也就是说,新的input()
函数从sys.stdin
读取一行,并返回去除尾随换行符的结果。如果输入提前结束,则会引发EOFError
异常。要获取input()
的旧行为,请使用eval(input())
在Python 2.7中,有两个函数可用于接受用户输入。一个是input
,另一个是raw_input
。你可以将它们之间的关系想象成:
input = eval(raw_input)
考虑以下代码片段以更好地理解此概念
>>> dude = "thefourtheye"
>>> input_variable = input("Enter your name: ")
Enter your name: dude
>>> input_variable
'thefourtheye'
input
接受用户输入的字符串,并在当前 Python 上下文中对其进行评估。当我输入 dude
时,它会发现 dude
绑定到值 thefourtheye
,因此评估结果变为 thefourtheye
并分配给 input_variable
。
如果我输入的其他内容不在当前的 Python 上下文中,它将失败并抛出 NameError
。
>>> input("Enter your name: ")
Enter your name: dummy
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'dummy' is not defined
Python 2.7的input
存在安全问题:
由于input
函数会评估用户输入的任何内容,因此它也会带来安全问题。例如,如果您在程序中已经使用import os
加载了os
模块,然后用户输入以下内容:
os.remove("/etc/hosts")
Python将把这个表达式作为函数调用表达式进行评估并执行。如果您使用提升的特权来执行Python,则/etc/hosts
文件将被删除。看看,它可能有多危险?
为了证明这一点,让我们再次尝试执行input
函数。
>>> dude = "thefourtheye"
>>> input("Enter your name: ")
Enter your name: input("Enter your name again: ")
Enter your name again: dude
现在,当执行 input("Enter your name: ")
时,它会等待用户输入,并且如果用户的输入是一个有效的 Python 函数调用,那么该函数也将被调用。这就是为什么我们再次看到了 Enter your name again:
提示。
因此,最好使用 raw_input
函数,像这样:
input_variable = raw_input("Enter your name: ")
如果您需要将结果转换为其他类型,那么您可以使用适当的函数来转换raw_input
返回的字符串。例如,要将输入读取为整数,请使用int
函数,如此答案所示。
在Python 3.x中,只有一个函数用于获取用户输入,它被称为input
,它等价于Python 2.7的raw_input
。
input
的行为是这样的,但只有在2.7中才会出现。当你从命令提示符运行python --version
时,它会说什么?或者,如果你在脚本开头写入import sys; print(sys.version)
,会发生什么? - Kevin