<p><strong>TL;DR</strong></p>
<p>Python 2.7中的<code>input</code>函数,作为Python表达式计算输入的内容。如果您只想读取字符串,那么在Python 2.7中使用<code>raw_input</code>函数,它不会计算读取的字符串。</p>
<p>如果您使用的是Python 3.x,<code>raw_input</code>已重命名为<code>input</code>。引用<a href="https://docs.python.org/3.0/whatsnew/3.0.html#builtins" rel="noreferrer">Python 3.0 release notes</a></p>
<blockquote>
<p><code>raw_input()</code> was renamed to <code>input()</code>. That is, the new <code>input()</code> function reads a line from <code>sys.stdin</code> and returns it with the trailing newline stripped. It raises <code>EOFError</code> if the input is terminated prematurely. To get the old behavior of <code>input()</code>, use <code>eval(input())</code></p>
</blockquote>
<hr/>
<p><strong>在Python2.7中,有两个函数可用于接受用户输入。一个是<a href="http://docs.python.org/2/library/functions.html#input" rel="noreferrer">^{<cd1>}</a>,另一个是<a href="http://docs.python.org/2/library/functions.html#raw_input" rel="noreferrer">^{<cd2>}</a>。你可以认为他们之间的关系如下</p>
<pre><code>input = eval(raw_input)
</code></pre>
<p>考虑下面的代码,以便更好地理解这一点</p>
<pre><code>>>> dude = "thefourtheye"
>>> input_variable = input("Enter your name: ")
Enter your name: dude
>>> input_variable
'thefourtheye'
</code></pre>
<p><code>input</code>接受来自用户的字符串,并在当前Python上下文中计算该字符串。当我键入<code>dude</code>作为输入时,它发现<code>dude</code>绑定到值<code>thefourtheye</code>,因此求值的结果变成<code>thefourtheye</code>,并分配给<code>input_variable</code>。</p>
<p>如果我输入了当前python上下文中不存在的其他内容,它将失败。</p>
<pre><code>>>> 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
</code></pre>
<p><strong>Python2.7的安全注意事项<code>input</code>:</strong></p>
<p>因为无论评估什么用户类型,它也会带来安全问题。例如,如果您已经用<code>import os</code>在程序中加载了<code>os</code>模块,然后用户输入</p>
<pre><code>os.remove("/etc/hosts")
</code></pre>
<p>python将其作为函数调用表达式进行计算并执行。如果使用提升的权限执行Python,则<code>/etc/hosts</code>文件将被删除。看,有多危险?</p>
<p>为了演示这一点,让我们再次尝试执行<code>input</code>函数。</p>
<pre><code>>>> dude = "thefourtheye"
>>> input("Enter your name: ")
Enter your name: input("Enter your name again: ")
Enter your name again: dude
</code></pre>
<p>现在,当执行<code>input("Enter your name: ")</code>时,它会等待用户输入,并且用户输入是一个有效的Python函数调用,因此也会被调用。这就是我们再次看到<code>Enter your name again:</code>提示的原因。</p>
<p>所以,最好使用<code>raw_input</code>函数,如下所示</p>
<pre><code>input_variable = raw_input("Enter your name: ")
</code></pre>
<p>如果需要将结果转换为其他类型,则可以使用适当的函数来转换<code>raw_input</code>返回的字符串。例如,要将输入读取为整数,请使用<code>int</code>函数,如<a href="https://stackoverflow.com/a/20449433/1903116">this answer</a>中所示。</p>
<p><strong>在python 3.x中,只有一个函数可以获取用户输入,称为<a href="http://docs.python.org/3/library/functions.html#input" rel="noreferrer">^{<cd1>}</a>,相当于python 2.7的<code>raw_input</code>。</p>