uTools-Manuals/docs/python/__main__.html
2019-04-21 11:50:48 +08:00

4 lines
1.8 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<div class="body" role="main"><div class="section" id="module-__main__"><h1><span class="yiyi-st" id="yiyi-10">29.4. </span><span class="yiyi-st" id="yiyi-11"><a class="reference internal" href="#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal"><span class="pre">__main__</span></code></a> — Top-level script environment</span></h1><p><span class="yiyi-st" id="yiyi-12"><code class="docutils literal"><span class="pre">'__main__'</span></code>是一个作用域的名称,顶层代码在这个作用域中执行。</span><span class="yiyi-st" id="yiyi-13">当从标准输入脚本或交互式提示读取时模块的__name__设置为等于<code class="docutils literal"><span class="pre">'__main__'</span></code></span></p><p><span class="yiyi-st" id="yiyi-14">模块可以通过检查它自己的<code class="docutils literal"><span class="pre">__name__</span></code>来发现它是否在主作用域中运行,这允许在作为脚本运行时或在<code class="docutils literal"> <span class="pre">python</span> <span class="pre">-m</span></code>但不导入时:</span></p><pre><code class="language-python"><span></span><span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span>
<span class="c1"># execute only if run as a script</span>
<span class="n">main</span><span class="p">()</span>
</code></pre><p><span class="yiyi-st" id="yiyi-15">对于包,通过包括<code class="docutils literal"><span class="pre">__main__.py</span></code>模块可以实现相同的效果,当模块以<code class="docutils literal"><span class="pre">-m</span></code>运行时,将执行该模块的内容。</span></p></div></div>