使用Python的input比raw_input有用吗?
使用Python的input比raw_input有用吗?
我目前在教授大学一年级的学生Python,并且我惊讶地发现,看起来无伤大雅的input
功能,有些学生已经决定使用它(并因其奇怪的行为感到困惑),实际上是在其后隐藏了调用eval
的函数。
所以我的问题是,为什么input
函数会调用eval
,这有什么用处,它无法使用raw_input
更安全地实现吗?我知道Python 3中已经更改了这种行为,但这似乎是一个不寻常的设计决策。
Python的输入函数返回一个对象,该对象是表达式评估的结果。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
运行示例:
示例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
示例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$
Q. 为什么输入函数调用eval?
A. 考虑用户在输入中输入表达式'45 + 7'的场景,输入函数将给出正确的结果,而Python 2.x中的raw_input则不会。
在使用Python 2时,使用input()
比raw_input()
有用吗?
不。
input()
评估用户所提供的代码。它使用户拥有Python的全部功能。使用生成器表达式/列表推导,__import__
和if/else
操作符,几乎可以实现任何Python可以做的事情。恶意用户可以使用input()
删除文件 (__import__('os').remove('precious_file')
),猴子补丁程序的其余部分 (setattr(__import__('__main__'), 'function', lambda:42)
)等任何事情。
正常用户不需要使用所有高级功能。如果不需要表达式,则使用 ast.literal_eval(raw_input())
– 安全的literal_eval
函数。
如果您正在为高级用户编写程序,请为他们提供更好的输入代码的方式。插件,用户模块等,具有完整的Python语法,而不仅仅是功能。
如果您绝对确定自己知道在做什么,请使用eval(raw_input())
。对于经验丰富的开发人员来说,eval
会让人想起“我很危险!”。但是,很可能您永远不需要这样做。
input()
是Python 3正在解决的旧设计错误之一。