在 Python 2 中,有两种获取输入的方法。 raw_input()
和 input()
,它是 eval(raw_input())
的包装器。然而,在 Python 3 中,input()
取代了 raw_input()
并且 input()
的旧含义已被弃用。这记录在 What's new in Python 3 中:
PEP 3111:
raw_input()
was renamed toinput()
. That is, the newinput()
function reads a line fromsys.stdin
and returns it with the trailing newline stripped. It raisesEOFError
if the input is terminated prematurely. To get the old behavior ofinput()
, useeval(input())
.
但是为什么 input()
一开始就出现在 Python 2 中呢?将用户输入评估为文字 Python 2 代码的基本原理是什么?这就是Python 2文档不得不说:
[
input()
is] Equivalent toeval(raw_input(prompt))
.This function does not catch user errors. If the input is not syntactically valid, a
SyntaxError
will be raised. Other exceptions may be raised if there is an error during evaluation.If the
readline
module was loaded, theninput()
will use it to provide elaborate line editing and history features.Consider using the
raw_input()
function for general input from users.
注意粗体部分(我强调的部分)。这到底是什么意思? I looked over the documentation for the readline
module并发现了一些东西。然而,我发现的唯一真正相关的部分是:
Settings made using this module affect the behavior of both the interpreter’s interactive prompt and the prompts offered by the
raw_input()
andinput()
built-in functions.
不过,这并不能真正帮助解释为什么首先要创建或需要 input()
。
不用说,使用 eval(any_user_input())
在安全方面是非常危险的,会导致调试困难,而且据我所知,速度很慢。那么,为什么他们首先要在 Python 2 中创建 input()
呢?开发人员在 input()
崩溃时没有意识到吗?
引用资料:
最佳答案
首先,能果断回答这个问题的大概只有the BDFL了。 .
input
在程序员使用的程序中很有用,这样他们就可以输入复杂的结构,比如 {'foo': 42}
,甚至表达式,但在旨在供不熟练用户使用的程序中则更少。
从 SCM 历史中我们可以看到 input
和 raw_input
were present in 1990; or pre-0.9 ,当 Python 处于起步阶段时 - 当时 exec
是一个函数,而 int('42')
会抛出异常。最值得注意的是,eval
也已经存在,因此即使在那时也可以使用 eval(raw_input())
来获得大部分相同的效果。
那时候没有Zen of Python然而,“唯一明显的方法”并不是指导原则,因此这可能是一种疏忽。
并且 raw_input
和 input
都保留了下来。在 Python 的历史中,向后兼容性是一个指导原则,因此 input
一直保持不变,直到向后不兼容的 Python 3 发布。
关于readline
模块的粗体部分:如果你导入readline
,那么你可以使用箭头键在input()上移动光标键
行和可配置的绑定(bind);如果程序中没有导入 readline
,则不存在这种行为。
同样,这并不是 input
最初存在的原因;回到 1990 年,Python 根本不支持,无论使用的是 input
还是 raw_input
。
关于python - 在 Python 2 中创建 input() 背后的基本原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40604113/