inputPython 2.7中的函数,作为Python表达式计算输入的内容。如果你只是想读取字符串,那么raw_input在Python 2.7中使用函数,它不会评估读取字符串。
如果您使用的是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: dummyTraceback (most recent call last):
File "", line 1, in
File "", line 1, in NameError: name 'dummy' is not defined
Python 2.7的安全注意事项input:
由于评估了任何用户类型,因此也会产生安全问题。例如,如果您已经os在程序中加载了模块import 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。