Python main函数的用法
Python作为一门较为灵活的解释型脚本语言,其中定义的main()函数只有当该Python脚本直接作为执行程序时才会执行;
当该python脚本被作为模块(module)引入(import)时,其中的main()函数将不会被执行。
举一个例子:
test1.py
'''
-*- coding: utf-8 -*-
@Author : Xinda Chen
@Time : 2021/4/8 19:46
@Software: PyCharm
@File : test1.py
'''
print('test1')
def main():
print('只有运行该文件才会执行')
if __name__ == '__main__':
main()
运行结果:
test2.py
'''
-*- coding: utf-8 -*-
@Author : Xinda Chen
@Time : 2021/4/8 19:49
@Software: PyCharm
@File : test2.py
'''
import test1
print('test2')
运行结果:
可以看到,“只有运行该文件才会执行”这句话在运行test2.py时不会输出