How to quickly, simply and rudely understand if __name__ =='__main__' in Python

1. Summary

Popular understanding __name__ == '__main__': If you are called Xiaoming.py, in the eyes of friends, you are Xiaoming (__name__ == '小明'); in your own eyes, you are yourself (__name__ == '__main__').

if __name__ == '__main__'The meaning is: when the .py file is run directly, if __name__ == '__main__'the code block below will be run; when the .py file is imported as a module, if __name__ == '__main__'the code block below will not be run.

2. Program Entry

For many programming languages, the program must have an entrance, such as C, C++, and fully object-oriented programming languages ​​Java, C#, etc. If you have been exposed to these languages, you should have a good understanding of the concept of program entry. Both C and C++ need to have a main function as the entry point of the program, that is, the running of the program will start from the main function. Similarly, Java and C# must have a main class containing the Main method as the program entry.

But Python is different. It belongs to a scripting language. Unlike a compiled language, the program is compiled into a binary and then run, but dynamically interpreted line by line. That is, it runs from the first line of the script, and there is no unified entry point.

In addition to being directly run, a Python source code file (.py) can also be used as a module (ie library) and imported by other .py files. Whether it is run directly or imported, the topmost code of the .py file will be run (Python uses indentation to distinguish code levels), and when a .py file is imported as a module, we may not want part of the code to be run.

2.1 A .py file is referenced by other .py files

Suppose we have a const.py file with the following content:

PI = 3.14

def main():
print("PI:", PI)

main()

# 运行结果:PI: 3.14

Now, we write an area.py file for calculating the area of ​​a circle. The area.py file needs to use the PI variable in the const.py file. From const.py, we import the PI variable into area.py:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from const import PI

def calc_round_area(radius):
return PI * (radius ** 2)

def main():
print("round area: ", calc_round_area(2))

main()

'''
运行结果:
PI: 3.14
round area: 12.56
'''

2.2 Modify const.py, addif __name__ == "__main__"

We see that the main function in const.py is also run. In fact, we don't want it to be run, because the main function provided by const.py is only for testing constant definitions. At this time, it if __name__ == '__main__'came in handy. We changed const.py and added if __name__ == "__main__":

PI = 3.14

def main():
print("PI:", PI)

if __name__ == "__main__":
main()

运行const.py,输出如下:

PI: 3.14

运行area.py,输出如下:

round area:  12.56

As above, we can see if __name__ == '__main__'the program entry equivalent to Python simulation. Python itself does not stipulate this. This is just a coding habit. Due to mutual references between modules, different modules may have such definitions, but there is only one program entry. Which program entry is selected depends on __name_the value of _.

3.__name__

3.1 __name__reflect the structure of a package

__name__It is a built-in variable that can be used to reflect the structure of a package. Suppose we have a package a, the structure of the package is as follows:

a
├── b
│ ├── c.py
│ └── __init__.py
└── __init__.py

In a package, a file c.py, __init__.py, __init__.pythe contents are as follows:

print(__name__)

When a .py file (module) is imported by another .py file (module), we execute it on the command line

python -c "import a.b.c"

输出结果:

a
a.b
a.b.c

This shows that it __name__can clearly reflect the level of a module in the package.

3.2 __name__Represents the name of the current module

__name__It is a built-in variable that can be used to represent the name of the current module. We run a .py file (module) directly

python a/b/c.py

输出结果:

__main__

From this we can know: If a .py file (module) is run directly, it has no package structure and its __name__value __main__is the module name __main__.

So, if __name__ == '__main__'the meaning is: when the .py file is run directly, if __name__ == '__main__'the code block below will be run; when the .py file is imported as a module, if __name__ == '__main__'the code block below will not be run.

4. __main__.pyFile and python -m

The -m parameter of Python is used to run a module or package as a script, and the __main__.pyfile is equivalent to the "entry program" of a package.

4.1 Two ways to run Python programs

  • python xxx.py, run the xxx.py file directly
  • python -m xxx.py, run xxx.py as a module

Suppose we have a file run.py with the following content:

import sys

print(sys.path)

We start it by running directly

python run.py

Output result (in order to illustrate the problem, only the important part of the output result is intercepted, the same below):

['/home/huoty/aboutme/pythonstudy/main', ...]

Then run it as a module:

python -m run.py

Output content

['', ...]
/usr/bin/python: No module named run.py

Since the output only lists the key parts, it should be easy to see the difference between them:

  • The direct operation method is to put the directory where the run.py file is located in the sys.path attribute

  • Running in module mode is to put the directory where you entered the command (that is, the current working path) into the sys.path attribute.

There is another difference when running in module mode: there is an extra line No module named run.pyof error. In fact, when running as a module, Python first performs an import to run.py, so print(sys.path) is successfully executed, and then Python tries to run the run.py module, but there is no run.py in the path variable. Module, so an error is reported. The correct way of operation should be python -m run.

4.2 __main__.pRole

Let's look at the example first, suppose we have the following package:

package
├── __init__.py
└── __main__.py

Among them, __init__.pythe content of the file

import sys

print("__init__")
print(sys.path)

Among them, __main__.pythe content of the file

import sys

print("__main__")
print(sys.path)

Next, we run this package, use python -m packagerun, and output the result:

__init__
['', ...]

__main__
['', ...]

Run with python package and output the result:

__main__
['package', ...]

in conclusion

When the -m parameter is added, Python will add the current working directory to sys.path; when -m is not added, Python will add the directory where the script is located to sys.path.

When the -m parameter is added, Python will first import the module or package and then execute it.

__main__.pyA file is the entry program of a package or directory. No matter it is run with python package or python -m package, the __main__.pyfile is always executed.

Guess you like

Origin blog.csdn.net/qdPython/article/details/112889360