Doubt (2) ----- How to understand if __name__ =='__main__' in Python in a simple way

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 of 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 entry point, such as C, C++, and fully object-oriented programming languages ​​Java, C#, etc. If you have been in contact with 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 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. Instead, it dynamically interprets and runs 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 (that is, a 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:

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()

Run const.py, the output is as follows:

PI: 3.14

Run area.py, the output is as follows:

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, it 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.
 

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 package a, c.py,__init__.py,__init__.pythe contents of the file are:

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"

Output result:

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

Output result:

__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 in the form of a module, if __name__ == '__main__'the code block below will not be run.

 

4.  __main__.pyDocuments andpython -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 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

  • To run 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 it print(sys.path)is successfully executed, and then Python tries to run the run.py module, but there is no run.py module in the path variable, so an error is reported. The correct way to operate, it should be python -m run.

4.2  __main__.pyRole

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__
['', ...]

Use python packageoperation, the output results:

__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. Regardless of whether it is used python packageor python -m packagerun, the __main__.pyfile is always executed.
     

5. Reference articles

1. How to understand if name  == ' main ' in Python 

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/113774675