|
发表于 2018-9-18 16:21:37
|
显示全部楼层
本帖最后由 令狐少侠 于 2018-9-18 16:23 编辑
Python 2.7中的input函数,作为Python表达式计算输入的内容。如果你只是想读取字符串,那么在Python 2.7中使用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。您可以如下考虑它们之间的关系
请考虑以下代码以更好地理解这一点
- >>> 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:
由于评估了任何用户类型,因此也会产生安全问题。例如,如果您已经在程序中加载了模块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。
|
|