2026-08-24 00:31:08
在Python中,if __name__ == "__main__": 是一个常见的惯用写法,用于判断当前模块是作为主程序运行,还是被其他模块导入。以下是对这一概念的详细解释:
1. Python程序的执行方式示例1:直接运行模块假设有一个名为hello.py的文件,内容如下:
print("first")def sayHello(): str = "hello" print(str) print(__name__ + ' from hello.sayhello()')if __name__ == "__main__": print('This is main of module "hello.py"') sayHello() print(__name__ + ' from hello.main')直接运行hello.py时,输出为:
firstThis is main of module "hello.py"hello__main__ from hello.sayhello()__main__ from hello.main第一行print("first")立即执行。
因为是直接运行,__name__为"__main__",所以条件块内的代码被执行。
示例2:模块被导入假设有另一个文件world.py,内容如下:
import helloif __name__ == "__main__": print('This is main of module "world.py"') hello.sayHello() print(__name__)运行world.py时,输出为:
firstThis is main of module "world.py"hellohello from hello.sayhello()__main__当import hello时,hello.py中的代码从上到下执行,包括print("first")。
但在hello.py中,__name__是"hello"(因为是被导入的),所以if __name__ == "__main__":块内的代码不会执行。
在world.py中,因为是直接运行,__name__为"__main__",所以条件块内的代码被执行。
通过这种方式,Python程序员可以灵活地控制代码的执行,同时保持代码的清晰和可维护性。