<p>关于可选地将模块用作主脚本的实用解决方案-支持一致的交叉导入:</p>
<h2>解决方案1:</h2>
<p>例如,在Python的pdb模块中,当执行为<code>__main__</code>(在末尾)时,如何通过导入自身将其作为脚本运行:</p>
<pre><code>#! /usr/bin/env python
"""A Python debugger."""
# (See pdb.doc for documentation.)
import sys
import linecache
...
# When invoked as main program, invoke the debugger on a script
if __name__ == '__main__':
import pdb
pdb.main()
</code></pre>
<p>只是我建议将<code>__main__</code>启动重新组织到脚本的开头,如下所示:</p>
<pre><code>#! /usr/bin/env python
"""A Python debugger."""
# When invoked as main program, invoke the debugger on a script
import sys
if __name__ == '__main__':
##assert os.path.splitext(os.path.basename(__file__))[0] == 'pdb'
import pdb
pdb.main()
sys.exit(0)
import linecache
...
</code></pre>
<p>这样模块体就不会被执行两次——这是“昂贵的”,不受欢迎的,有时是至关重要的。</p>
<h2>解决方案2:</h2>
<p>在较少见的情况下,需要公开实际的脚本模块<code>__main__</code>,甚至直接作为实际的模块别名(<code>mod1</code>):</p>
<pre><code># mod1.py
import mod2
...
if __name__ == '__main__':
# use main script directly as cross-importable module
_mod = sys.modules['mod1'] = sys.modules[__name__]
##_modname = os.path.splitext(os.path.basename(os.path.realpath(__file__)))[0]
##_mod = sys.modules[_modname] = sys.modules[__name__]
func1A()
</code></pre>
<p>已知缺点:</p>
<ul>
<li><code>reload(_mod)</code>失败</li>
<li>pickle类需要额外的映射来取消绑定(<code>find_global</code>..)</li>
</ul>