当通过将脚本作为命令传递给Python解释器来运行脚本时,
python myscript.py
将执行缩进级别为0的所有代码定义的函数和类是定义好的,但它们的代码都不能运行不像其他语言
main()
自动运行的函数-
主()
函数隐式地表示顶层的所有代码。
在本例中,顶级代码是
if
封锁。
__name__
是一个内置变量,其计算结果为当前模块的名称但是,如果直接运行模块(如
myscript.py
以上),然后
__姓名__
而是设置为字符串
"__main__"
. 因此,可以通过测试来测试脚本是直接运行还是由其他东西导入
if __name__ == "__main__":
...
如果您的脚本被导入到另一个模块中,则会导入其各种函数和类定义,并执行其顶层代码,但是
如果
由于不满足条件,上面的子句将无法运行。作为基本示例,请考虑以下两个脚本:
# file one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
现在,如果您调用解释器作为
python one.py
输出将是
top-level in one.py
one.py is being run directly
如果你跑
two.py
相反:
python two.py
你得到
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
因此,当模块
one
加载,它的
__姓名__
等于
"one"
而不是
“主要”
.