python __name__ 全局变量给出与预期不同的输出
python __name__ global variable gives different output than expected
我正在尝试动手实践 python 个模块。
我的代码是,
#filename:module.py
def printname():
print __name__
printname()
当我用解释器执行代码时
python module.py
它给出输出(即模块名称为)
main
当我将模块导入另一个文件并在那里调用模块时,它会以模块名称(预期)的形式给出输出。
module
根据docs,它应该给出模块名称作为输出。为什么输出会发生变化??
主脚本总是调用__main__
。这是完全正确的行为。
从您链接到的同一页面,
在 preceding Executing modules as scripts section 中,您会发现:
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the __name__
set to "__main__"
.
对于您 import 的所有内容,__name__
将反映它最初可用的模块名称。
另见 Interface options documentation:
<script>
[...]
If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__
module.
和 __main__
Top-level script environment documentation:
This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt.
我正在尝试动手实践 python 个模块。
我的代码是,
#filename:module.py
def printname():
print __name__
printname()
当我用解释器执行代码时
python module.py
它给出输出(即模块名称为)
main
当我将模块导入另一个文件并在那里调用模块时,它会以模块名称(预期)的形式给出输出。
module
根据docs,它应该给出模块名称作为输出。为什么输出会发生变化??
主脚本总是调用__main__
。这是完全正确的行为。
从您链接到的同一页面, 在 preceding Executing modules as scripts section 中,您会发现:
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the
__name__
set to"__main__"
.
对于您 import 的所有内容,__name__
将反映它最初可用的模块名称。
另见 Interface options documentation:
<script>
[...]
If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the
__main__
module.
和 __main__
Top-level script environment documentation:
This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt.