Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

18. Python main 函数

Python main函数只在作为Python程序执行时执行。如你所知,我们也可以进口一个python程序作为一个模块,在这种情况下python main方法不应该执行。

Python主函数

Main函数是任何程序的入口点。但是python解释器按顺序执行源文件代码,如果它不是代码的一部分,则不会调用任何方法。但是如果它直接是代码的一部分,那么它将在文件作为模块导入时执行。

这就是为什么在python程序中有一种特殊的方法来定义main方法,这样它只在程序直接运行时执行,而在作为模块导入时不执行。让我们看看如何在一个简单的程序中定义python main函数。

python_main_function.py


print("Hello")

print("__name__ value: ", __name__)


def main():
    print("python main function")


if __name__ == "__main__":
    main()
  • 当一个python程序被执行时,python解释器开始在它内部执行代码。它还设置了一些隐式变量值,其中之一是__name__ whose value is set as __main__.
  • 对于python main函数,我们必须定义一个功能然后使用if __name__ == "__main__" condition to execute this function.
  • 如果python源文件作为模块,python解释器设置__name__ value to module name, so the if condition will return false and main method will not be executed.
  • Python为我们提供了保留main方法的任何名称的灵活性,但是最好将其命名为main()方法。下面的代码很好,但不推荐使用。
    
    def main1():
        print("python main function")
    
    
    if __name__ == "__main__":
        main1()
    

下图显示了当python_main_function.py is executed as source file.

Python主函数作为模块

现在让我们使用上面的python源文件作为模块并导入到另一个程序中。

python_import.py


import python_main_function

print("Done")

现在当上面的程序被执行时,下面的输出就产生了。


Hello
__name__ value:  python_main_function
Done

请注意,前两行是从python_main_function.py source file. Notice the value of __name__ is different and hence main method is not executed.

请注意,python程序语句是逐行执行的,因此在执行main方法的if条件之前先定义main()方法很重要。否则,您将得到错误NameError: name "main" is not defined.

这就是python主函数的全部内容。

参考文献:Python文档