<ol>
<li><p><code>exec</code>不是表达式:Python 2.x中的语句和Python 3.x中的函数。它编译并立即计算字符串中包含的语句或语句集。例如:</p>
<pre><code> exec('print(5)') # prints 5.
# exec 'print 5' if you use Python 2.x, nor the exec neither the print is a function there
exec('print(5)\nprint(6)') # prints 5{newline}6.
exec('if True: print(6)') # prints 6.
exec('5') # does nothing and returns nothing.
</code></pre>
</li>
<li><p><code>eval</code>是一个内置函数(<strong>不是</strong>语句),它对表达式求值并返回表达式生成的值。例如:</p>
<pre><code> x = eval('5') # x <- 5
x = eval('%d + 6' % x) # x <- 11
x = eval('abs(%d)' % -100) # x <- 100
x = eval('x = 5') # INVALID; assignment is not an expression.
x = eval('if 1: x = 4') # INVALID; if is a statement, not an expression.
</code></pre>
</li>
<li><p><code>compile</code>是<code>exec</code>和<code>eval</code>的较低级别版本。它不会执行或计算语句或表达式,但会返回一个可以执行该操作的代码对象。模式如下:</p>
</li>
<li><p><code>compile(string, '', 'eval')</code>返回如果执行了<code>eval(string)</code>将执行的代码对象。请注意,在此模式下,<em>不能</em>使用语句;只有一个(单个)表达式有效</p>
</li>
<li><p><code>compile(string, '', 'exec')</code>返回如果执行<code>exec(string)</code>将执行的代码对象。您可以在这里使用任意数量的语句</p>
</li>
<li><p><code>compile(string, '', 'single')</code>类似于<code>exec</code>模式,但只需要一个表达式/语句,例如<code>compile('a=1 if 1 else 3', 'myf', mode='single')</code></p>
</li>
</ol>