导入我的模块使程序 运行 独立

Importing my module makes the program run on its own

我有一个 python 程序用作计算器。我决定学习如何将它导入其他程序,所以我添加了:

if __name__ == "__main__":
    main()

我已经多次尝试导入我的模块,它所做的只是 运行 主要功能,只有编辑器上的导入语句。我所做的就是输入 import calculator,它只是 运行 而已。我不太确定 if name 语句的作用是什么,如果有人也能详细说明它如何帮助导入我的程序,那就太好了。

see here 有关 if __name__ == "__main__" 的更多信息,但快速摘录是

Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.

因此,如果您调用 python mymodule.pyif __name__ == "__main__" 块中包含的任何代码都只会是 运行。如果您调用 python importsmymodule.py,它不会 运行。

至于你的具体问题,没有看到计算器模块的代码就无法判断,但似乎不言自明的是你脚本中的某些东西正在调用计算器来开始。

if __name__ == "__main__": main() 条件检查您是否通过 python 解释器 运行 运行脚本并调用 main() 函数。更详细的解释参考这个问题What does if name == “main”: do?

如果你有这样的程序

# script.py
def hello_world():
    print "Hello World!"

hello_world()

if __name__ == "__main__":
    main()

Hello World! 无论你从像 python script.py 这样的命令行导入 script.py 还是 运行 都会打印出来,因为函数 hello_world() 在两者中都执行实例。

案例 1:运行 来自命令行

$ python script.py
Hello World!
Traceback (most recent call last):
  File "/path/to/tests/script.py", line 8, in <module>
    main()
NameError: name 'main' is not defined

案例 2:作为模块导入

>>> import script
Hello World!

如果你想阻止它被打印,那么将代码的执行部分包装在 main 函数中,如下所示:

def hello_world():
        print "Hello World!"

def main():
    hello_world()

if __name__ == "__main__":
    main() 

现在,hello_world() 只有当您 运行 作为脚本而不是作为模块导入时才会被调用(或 Hello World! 被打印)。