<p>变量<code>__name__</code>始终包含模块名,<em>,除非文件已作为脚本加载到解释器中。<em>然后将该变量设置为字符串<code>'__main__'</code>。</p>
<p>毕竟,脚本作为整个程序的主文件运行,其他的都是由主文件直接或间接导入的模块。通过测试<code>__name__</code>变量,可以检测文件是作为模块导入的,还是直接运行的。</p>
<p>在内部,在<code>sys.modules</code>中为模块提供了一个名称空间字典,该字典作为每个模块的元数据的一部分存储。主文件,即执行的脚本,存储在与<code>'__main__'</code>相同的结构中。</p>
<p>但是当您将一个文件作为模块导入时,python首先在<code>sys.modules</code>中查看该模块以前是否已经导入过。因此,<code>import mod1</code>意味着我们首先在<code>sys.modules</code>中查找<code>mod1</code>模块。如果<code>mod1</code>还不存在,它将创建一个带有名称空间的新模块结构。</p>
<p>因此,如果您同时运行<code>mod1.py</code>作为主文件,<em>和</em>稍后将其作为python模块导入,它将在<code>sys.modules</code>中获得两个<em>命名空间条目。一个是<code>'__main__'</code>,然后是<code>'mod1'</code>。这两个名称空间是完全分离的。您的全局<code>var1</code>存储在<code>sys.modules['__main__']</code>中,但是<code>func1B</code>正在<code>sys.modules['mod1']</code>中查找<code>var1</code>,其中是<code>None</code>。</p>
<p>但是当您使用<code>python driver.py</code>时,<code>driver.py</code>将成为程序的<code>'__main__'</code>主文件,并且<code>mod1</code>将只被导入到<code>sys.modules['mod1']</code>结构中一次。这一次,<code>func1A</code>将<code>var1</code>存储在<code>sys.modules['mod1']</code>结构中,这就是<code>func1B</code>将找到的。</p>