Python if __name__ == understood '__main__' of

1. Summary

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

if __name__ == '__main__'Means: when the file is run directly .py, the if __name__ == '__main__'code block is under operation; .py file when the module is introduced in the form of if __name__ == '__main__'code blocks is not under operation.

 

2. The program entry

For many programming languages, the program must have an entry, such as C, C ++, and a fully object-oriented programming language Java, C # and so on. If you come into contact with these languages, the program entry for this concept should be well understood, C, C ++ needs to have a main function as the entry program, which is run the program will start from the main function. Similarly, Java, C # must have a Main method comprising main class, as the program entry.

The Python is different, it belongs to the scripting language, unlike compiled languages ​​like compiled into binary program first run, but a dynamic progressive interpretation run. That is run from the first line of the script, there is no uniform entrance.

A Python source file (.py) in addition may be run directly, but also as a module (i.e. library), is introduced into the other .py files. Either directly run or imported, .py file of the top level code that will be run (Python use indentation to distinguish the code level), and when a .py file is imported as a module, we may not want to be part of the code to run.

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

Suppose we have a const.py file, as follows:

PI = 3.14

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

main()

# 运行结果:PI: 3.14

Now, we write a for calculating the area of ​​a circle area.py file, file area.py need to use PI variable const.py file. From const.py, we put PI variable import 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 const.py the main function was also run, in fact, we do not want it to be run because the main function const.py provided just to test the constants defined. Then if __name__ == '__main__'came in handy, we const.py change it, add if __name__ == "__main__":

PI = 3.14

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

if __name__ == "__main__":
    main()

Run const.py, output:

PI: 3.14

Run area.py, output:

round area:  12.56

As we can see if __name__ == '__main__'the equivalent of Python simulation program entry, Python itself is not so specified, this is just a coding habits. Since the mutual references between the modules, different modules may have such a definition, and only a program entry. Which in the end the program entry is selected, depending on the __name__value.
 

3. __name__

3.1 __name__reflect the structure of a package

__name__A built-in variable, it may be used to reflect the structure of a packet. Suppose we have a packet a, the packet structure is as follows:

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

In a package, the file c.py,__init__.py,__init__.pycontents are as follows:

print(__name__)

When a .py file (module) is (module) import other .py files, we execute the command line

python -c "import a.b.c"
  • Output:
a
a.b
a.b.c

This shows __name__clearly reflect a hierarchy of modules in the package.

3.2 __name__represents the name of the current module

__name__A built-in variables it can be used to indicate the name of the current module. We directly run a .py file (module)

python a/b/c.py

Output:

__main__

Thus we found that: if a .py file (module) is operated directly, then it is no packet structure, which __name__is __main__, i.e., the module name __main__.

Therefore, if __name__ == '__main__'means: when the file is run directly .py, the if __name__ == '__main__'code block is under operation; .py file when the module is introduced in the form of if __name__ == '__main__'code blocks is not under operation.

 

4. __main__.pyfilepython -m

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

Python 4.1 are two ways to run the program

  • python xxx.pyRun directly xxx.py file
  • python -m xxx.py, The module is running as xxx.py

Suppose we have a file run.py, reads as follows:

import sys

print(sys.path)

We started with the direct running

python run.py

The output (For illustrative purposes, only the output intercept an important part of, the same below):

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

Then run in a modular way:

python -m run.py
  • Output content
['', ...]
/usr/bin/python: No module named run.py

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

  • Direct operating mode is the directory where the file run.py put sys.path attribute

  • Run in a modular fashion that you enter the command catalog (which is the current working directory), put sys.path attribute.

To run the module there is a different place: a line of more than a No module named run.pymistake. In fact when running in a modular fashion, the first implementation of the Python run.py again import, it print(sys.path)is executed successfully, and then try to run run.py module Python before, but did not run.py this module in the path variable, so an error. The correct way to run, it should be python -m run.

4.2 __main__.pyrole

Still look at an example, suppose we have as a package package:

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

Among them, the file __init__.pycontent

import sys

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

Among them, the file __main__.pycontent

import sys

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

Next, we run this package, use python -m packageoperation, the output results:

__init__
['', ...]

__main__
['', ...]
  • Use python packageoperation, the output results:
__main__
['package', ...]

in conclusion

  • When combined with -m parameter, Python will add to the current working directory in sys.path; the time without adding -m, Python scripts will be added to the directory in sys.path.

  • When adding -m parameters, Python be introduced into the first module or a package, and then executed.

  • __main__.pyAn entry program is a package file or directory. Whether with python packageor used python -m packageto run, __main__.pythe file is always executed.
     

5. Reference article

1. Python the IF name == ' main ' how to understand

--------------------- Locutus article from the CSDN blog, please click the full text of the address: https: //blog.csdn.net/yjk13703623757/article/details/77918633 ? utm_source = copy

Published 35 original articles · won praise 61 · views 160 000 +

Guess you like

Origin blog.csdn.net/woailyoo0000/article/details/82983938