python - 在 Python 2 中创建 input() 背后的基本原理是什么?

标签 python input eval python-2.x python-internals

在 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 to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

但是为什么 input() 一开始就出现在 Python 2 中呢?将用户输入评估为文字 Python 2 代码的基本原理是什么?这就是Python 2文档不得不说:

[input() is] Equivalent to eval(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, then input() 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() and input() built-in functions.

不过,这并不能真正帮助解释为什么首先要创建或需要 input()

不用说,使用 eval(any_user_input()) 在安全方面是非常危险的,会导致调试困难,而且据我所知,速度很慢。那么,为什么他们首先要在 Python 2 中创建 input() 呢?开发人员在 input() 崩溃时没有意识到吗?

引用资料:

最佳答案

首先,能果断回答这个问题的大概只有the BDFL了。 .

input 在程序员使用的程序中很有用,这样他们就可以输入复杂的结构,比如 {'foo': 42},甚至表达式,但在旨在供不熟练用户使用的程序中则更少。

从 SCM 历史中我们可以看到 inputraw_input were present in 1990; or pre-0.9 ,当 Python 处于起步阶段时 - 当时 exec 是一个函数,而 int('42') 会抛出异常。最值得注意的是,eval 也已经存在,因此即使在那时也可以使用 eval(raw_input()) 来获得大部分相同的效果。

那时候没有Zen of Python然而,“唯一明显的方法”并不是指导原则,因此这可能是一种疏忽。

并且 raw_inputinput 都保留了下来。在 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/

相关文章:

python - 如何为彩色散点图创建图例而不是颜色条?

python - 检查输入是否是循环中的字符串

javascript - 将输入控件的文件列表设置为先前选择的文件列表

php - 我可以用变量调用方法吗?

javascript - EVAL 危险 如何更换

python - 如何使用 tweepy 从带有地理标记的推文中获取位置?

python - 如何使 python 类满足 SWIG 中的接口(interface)?

python - Pandas 从系列中获取月末值

c - 从 c 中的用户输入中读取 2 个整数

php - Laravel - 带有 blade compileString 的 php eval