python - 为什么在Python中使用 "if __name__==' __main_ _': main()"而不是简单的 "main()"?

标签 python program-entry-point

另外,为什么我们要使用下划线?毕竟我将main方法定义为main() ,而不是 __main__() .

最佳答案

When the Python interpreter reads a source file, it executes all of the code found in it. 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.

In the case of your script, let's assume that it's executing as the main function, e.g. you said something like

python threading_example.py

on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that __name__ does equal "__main__", so it will execute the block shown there.

One of the reasons for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

取自这里:What does if __name__ == "__main__": do?

关于python - 为什么在Python中使用 "if __name__==' __main_ _': main()"而不是简单的 "main()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18506274/

相关文章:

python - 导入日期时间与从日期时间导入日期时间

python - 如果我有一个类的单个实例,最好是让它全局化还是作为构造函数中的参数传递?

python - PySpark - 将列表作为参数传递给 UDF

c++ - 从 main 访问私有(private)字段和函数

python - 如何从 Python 脚本返回一个值作为 Bash 变量?

python - 如何从 Google 代码进行 pip 安装?

python - 为什么scrapy没有给出所有结果并且规则部分也不起作用?

java - 如何创建一种方法来计算从 4+ 方法中获取变量来进行计算?

c++ - 使用 .h 扩展名

c++ - 希望定期执行一个函数,但继续执行其余的程序循环