<p>从这里:<a href="https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python">What's the difference between eval, exec, and compile in Python?</a>:</p>
<p><code>compile</code>是<code>exec</code>和<code>eval</code>的低级版本。它不执行或计算您的语句或表达式,但返回可以执行此操作的代码对象。模式如下:</p>
<ol>
<li><code>compile(string, '', 'eval')</code>返回完成<code>eval(string)</code>时将执行的代码对象。注意,<em>不能在此模式下使用语句;只有(单个)表达式有效。在</li>
<li><code>compile(string, '', 'exec')</code>返回完成<code>exec(string)</code>时将执行的代码对象。这里可以使用任意数量的语句。在</li>
<li><code>compile(string, '', 'single')</code>类似于<code>exec</code>模式,但它将忽略除第一个语句之外的所有内容。注意,<code>if</code>/<code>else</code>语句及其结果被视为单个语句。在</li>
</ol>
<p>更新:</p>
<p>何时编译Python?</em></strong></p>
<p>通常编译Python是为了利用性能。编译后的代码不需要编译,所以启动时间要快得多,但它的运行速度并不比编译的快。在</p>
<p>最值得注意的是,如果您想手工将代码转换为字节码,您可以使用<code>compile</code>。这就引出了另一个重要但相关的问题<strong>为什么要这样做?在</p>
<p>如本<a href="http://lucumr.pocoo.org/2011/2/1/exec-in-python/" rel="nofollow noreferrer">magnificent article</a>中所述:</p>
<blockquote>
<p>if you want to use exec and you plan on executing that code more than
once, make sure you compile it into bytecode first and then execute
that bytecode only and only in a new dictionary as namespace.</p>
</blockquote>
<p>特别值得注意的是:</p>
<blockquote>
<p>Now how much faster is executing bytecode over creating bytecode and
executing that?:</p>
<p>$ python -mtimeit -s 'code = "a = 2; b = 3; c = a * b"' 'exec code'
10000 loops, best of 3: 22.7 usec per loop</p>
<p>$ python -mtimeit -s 'code = compile("a = 2; b = 3; c = a * b",<br/>
"", "exec")' 'exec code' 1000000 loops, best of 3: 0.765 usec
per loop</p>
<p><strong>32 times as fast for a very short code example.</strong> It becomes a lot worse
the more code you have. Why is that the case? <strong>Because parsing Python
code and converting that into Bytecode is an expensive operation
compared to evaluating the bytecode.</strong> That of course also affects
<code>execfile</code> which totally does not use bytecode caches, how should it.
It's not gonna magically check if there is a <code>.pyc</code> file if you are
passing the path to a <code>foo.py</code> file.</p>
</blockquote>