“Python/docs/3.9/library/ main”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/ main
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:__main__ — 顶级脚本环境 — Python 文档}}
 
<div id="module-__main__" class="section">
 
<div id="module-__main__" class="section">
  
 
<span id="main-top-level-script-environment"></span>
 
<span id="main-top-level-script-environment"></span>
= [[#module-__main__|<code>__main__</code>]] --- Top-level script environment =
+
= __main__ — 顶级脚本环境 =
  
<code>'__main__'</code> is the name of the scope in which top-level code executes.
 
A module's __name__ is set equal to <code>'__main__'</code> when read from
 
standard input, a script, or from an interactive prompt.
 
  
A module can discover whether or not it is running in the main scope by
+
-----
checking its own <code>__name__</code>, which allows a common idiom for conditionally
+
 
executing code in a module when it is run as a script or with <code>python -m</code> but not when it is imported:
+
<code>'__main__'</code> 是顶级代码执行的范围的名称。 当从标准输入、脚本或交互式提示中读取时,模块的 __name__ 被设置为等于 <code>'__main__'</code>
 +
 
 +
模块可以通过检查自己的 <code>__name__</code> 来发现它是否在主作用域中运行,这允许在模块作为脚本或使用 运行时有条件地执行代码的通用习惯用法X212X] 但在导入时不是:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第16行: 第16行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>if __name__ == &quot;__main__&quot;:
+
<syntaxhighlight lang="python3">if __name__ == "__main__":
 
     # execute only if run as a script
 
     # execute only if run as a script
     main()</pre>
+
     main()</syntaxhighlight>
 +
 
 +
</div>
  
 
</div>
 
</div>
 +
对于一个包,通过包含一个 <code>__main__.py</code> 模块可以达到同样的效果,当模块与 <code>-m</code> 一起运行时,模块的内容将被执行。
 +
  
 
</div>
 
</div>
For a package, the same effect can be achieved by including a
+
<div class="clearer">
<code>__main__.py</code> module, the contents of which will be executed when the
+
 
module is run with <code>-m</code>.
 
  
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:51的最新版本

__main__ — 顶级脚本环境


'__main__' 是顶级代码执行的范围的名称。 当从标准输入、脚本或交互式提示中读取时,模块的 __name__ 被设置为等于 '__main__'

模块可以通过检查自己的 __name__ 来发现它是否在主作用域中运行,这允许在模块作为脚本或使用 运行时有条件地执行代码的通用习惯用法X212X] 但在导入时不是:

if __name__ == "__main__":
    # execute only if run as a script
    main()

对于一个包,通过包含一个 __main__.py 模块可以达到同样的效果,当模块与 -m 一起运行时,模块的内容将被执行。