luk*_*son 31 python user-input python-2.x
我目前教大学一年级学生python,我很惊讶地发现,input我的一些学生已经决定使用(并且被奇怪的行为搞糊涂了)看似无害的功能,正在隐藏eval它背后的电话.
所以我的问题是,input函数调用的原因是eval什么,以及这对哪些函数更有用raw_input呢?我知道Python 3已经改变了,但它首先似乎是一个不寻常的设计决定.
Pet*_*rin 38
在raw_input上使用Python 2的输入是否有用?
没有.
input()评估用户给出的代码.它将Python的全部功能掌握在用户手中.使用生成器表达式/列表推导,__import__以及if/else运算符,Python可以通过单个表达式完成任何操作.恶意用户可以使用input()删除文件(__import__('os').remove('precious_file')),monkeypatch程序的其余部分(setattr(__import__('__main__'), 'function', lambda:42)),......任何东西.
普通用户不需要使用所有高级功能.如果您不需要表达式,请使用ast.literal_eval(raw_input())- 该literal_eval函数是安全的.
如果您是为高级用户编写的,请为他们提供更好的输入代码的方法.插件,用户模块等 - 具有完整Python语法的东西,而不仅仅是功能.
如果你完全确定你知道自己在做什么,请说eval(raw_input()).在eval尖叫"我危险了!" 受过训练的眼睛.但是,你很可能不会需要这个.
input() 是Python 3正在解决的旧设计错误之一.
Python Input函数返回一个对象,该对象是评估表达式的结果.raw_input函数返回一个字符串
name = "Arthur"
age = 45
first = raw_input("Please enter your age ")
second = input("Please enter your age again ")
# first will always contain a string
# second could contain any object and you can even
# type in a calculation and use "name" and "age" as
# you enter it at run time ...
print "You said you are",first
print "Then you said you are",second
Run Code Online (Sandbox Code Playgroud)
运行的例子:
示例:1
Prompt$ python yraw
Please enter your age 45
Please enter your age again 45
You said you are 45 Then you said you are 45
Run Code Online (Sandbox Code Playgroud)
示例:2
Prompt$ python yraw
Please enter your age 45 + 7
Please enter your age again 45 + 7
You said you are 45 + 7 Then you said you are 52
Prompt$
Run Code Online (Sandbox Code Playgroud)
问:为什么输入函数调用eval?
A.考虑用户在输入中输入表达式'45 + 7'的情况,与python 2.x中的raw_input相比,输入将给出正确的结果
| 归档时间: |
|
| 查看次数: |
4675 次 |
| 最近记录: |