1. Abstract
Popular understanding __name__ == '__main__'
: if your name is Xiaoming.py, in the eyes of friends, you are Xiaoming (__name__ == '小明')
; in your own eyes, you are yourself (__name__ == '__main__')
.
if __name__ == '__main__'
It means: 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, programs must have an entry, 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 a main function as the entry of the program, that is, the running of the program will start from the main function. Similarly, Java, C# must have a main class that contains the Main method as the program entry.
Python is different. It belongs to a scripting language. Unlike compiled languages, the program is first compiled into binary and then run. Instead, it is dynamically interpreted line by line. That is, it runs from the first line of the script, and there is no unified entry.
In addition to being run directly, a Python source 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 top-level 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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Now, let's 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
'''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
2.2 Modify const.py and 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 if __name__ == '__main__'
, it comes in handy. We change const.py and add if __name__ == "__main__"
:
PI = 3.14
def main():
print("PI:", PI)
if __name__ == "__main__":
main()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Running const.py, the output is as follows:
PI: 3.14
- 1
Running area.py, the output is as follows:
round area: 12.56
- 1
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. Since modules refer to each other, different modules may have such definitions, and there is only one program entry. Exactly which program entry is selected depends on __name__
the value of .
3.__name__
3.1 __name__
Reflecting the structure of a package
__name__
are built-in variables 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
- 1
- 2
- 3
- 4
- 5
In package a, c.py,__init__.py,__init__.py
the contents of the files are:
print(__name__)
- 1
When a .py file (module) is imported by another .py file (module), we execute on the command line
python -c "import a.b.c"
- 1
Output result:
a
a.b
a.b.c
- 1
- 2
- 3
It can be seen that __name__
the level of a module in the package can be clearly reflected.
3.2 __name__
Indicates the name of the current module
__name__
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
- 1
Output result:
__main__
- 1
From this we know that 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__.py
Document andpython -m
Python's -m parameter is used to run a module or package as a script, and the __main__.py
file 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 directlypython -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)
- 1
- 2
- 3
We start with direct operation
python run.py
- 1
The 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', ...]
- 1
Then run it as a module:
python -m run.py
- 1
output content
['', ...]
/usr/bin/python: No module named run.py
- 1
- 2
Since only the critical parts are listed in the output, it should be easy to see the difference:
-
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 puts the directory you entered the command into (that is, the current working path) into the sys.path property.
There's one more difference to running as a module: an extra line No module named run.py
of errors. In fact, when running in module mode, Python first executes the import of 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 run, it should be python -m run
.
4.2 __main__.py
The role
Still looking at the example first, suppose we have the following package:
package
├── __init__.py
└── __main__.py
- 1
- 2
- 3
Among them, __init__.py
the content of the file
import sys
print("__init__")
print(sys.path)
- 1
- 2
- 3
- 4
Among them, __main__.py
the content of the file
import sys
print("__main__")
print(sys.path)
- 1
- 2
- 3
- 4
Next, we run the package, use python -m package
run, and output the result:
__init__
['', ...]
__main__
['', ...]
- 1
- 2
- 3
- 4
- 5
Use python package
run to output the result:
__main__
['package', ...]
- 1
- 2
in conclusion
-
When the -m parameter is added, Python will add the current working directory to sys.path; without -m, 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__.py
A file is the entry program for a package or directory. The file is always executed regardless of whether it is usedpython package
orpython -m package
run .__main__.py