Blog.csdn.net/yjk13703623…

A, in this paper,

Popular understanding __name__ = = “__main__ ‘: if your name is xiao Ming. Py, in the eyes of friends, you are xiao Ming (__name__ = =’ Ming ‘); In your own eyes, you are yourself (__name__ == ‘__main__’).

If __name__ = = “__main__ ‘means: when. Py file is run directly, if __name__ = =” __main__’ under the block of code will be run; When the.py file is imported as a module, blocks of code under if __name__ == ‘__main__’ are not run.

2. Program entry

For many programming languages, programs must have an entry point, such as C, C++, and fully object-oriented programming languages such as Java and C#. If you’re familiar with any of these languages, the concept of an entry point should be fairly straightforward. Both C and C++ require a main function as an entry point to a program. Similarly, Java, C# must have a Main class containing the Main method as an entry point.

Python, on the other hand, is a scripting language. Unlike compiled languages, which compile programs into binary and then run them, Python dynamically interprets them line by line. That is, run from the first line of the script. There is no uniform entry point.

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

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

Suppose we have a const. Py file that looks like this:

Def main(): print("PI:", PI) main() #Copy the code

Now, let’s write an area.py file that calculates the area of the circle. The area.py file uses the PI variable in the conconst. From conconst. 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()"Copy the code

2.2 Modify const. Py by adding if __name__ == “__main__”

We see that main in conconst. Py is also run, which we really don’t want to run, because the main function provided by conconst. Py is just for testing constant definitions. At this moment if __name__ = = “__main__ ‘come in handy, we put the const. Py change, add the if __name__ = =” __main__ “:

PI = 3.14 def main () : print (" PI ", PI) if __name__ = = "__main__" : the main ()Copy the code

Run consent.py and the output looks like this:

PI: 3.14
Copy the code

Run area.py and the output looks like this:

Round area: 12.56Copy the code

As we can see above, if __name__ == ‘__main__’ is equivalent to the program entry for Python emulation. Python itself does not specify this; it is just a coding convention. Because modules reference each other, different modules may have such a definition, and there is only one program entry. Which program entry is selected depends on the value of __name__.

3. __name__

3.1 __name__ reflects the structure of a package

__name__ is a built-in variable that reflects the structure of a package. Suppose we have a package A with the following structure:

A ├ ─ ─ b │ ├ ─ ─ c.p y │ └ ─ ─ just set py └ ─ ─ just set pyCopy the code

In package A, the files c.py, __init__. Py, __init__.

print(__name__)1
Copy the code

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

python -c "import a.b.c"1
Copy the code

Output result:

a
a.b
a.b.c123
Copy the code

Thus, __name__ is a clear reflection of a module’s hierarchy in a package.

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’ll just run a.py file (module)

python a/b/c.py1
Copy the code

Output result:

__main__1
Copy the code

If a.py file (module) is run directly, it has no package structure and its __name__ value is __main__, that is, the module name __main__.

So, if __name__ = = “__main__ ‘means: when. Py file is run directly, if __name__ = =” __main__’ under the block of code will be run; When the.py file is imported as a module, blocks of code under if __name__ == ‘__main__’ are not run.

4. __main__.py files with python -m

Python’s -m argument is used to run a module or package as a script, and the __main__.py file is a package entry.

4.1 Two ways to run Python programs

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

Suppose we have a file run.py that looks like this:

import sys

print(sys.path)123
Copy the code

We start with a direct run

python run.py1
Copy the code

Output results (for illustrative purposes, only important portions of the output are extracted, similarly below) :

['/home/huoty/aboutme/pythonstudy/main', ...] 1Copy the code

Then run as a module:

python -m run.py1
Copy the code

output

[' '...  /usr/bin/python: No module named run.py12Copy the code

Since the output only lists the key sections, it should be easy to see how they differ:

  • The direct way to do this is to put the directory of the run.py file in the sys.path property

  • Running as a module puts the directory where you typed the command (the current working path) into the sys.path property.

Running as a module is also different: there is an extra line of error No module named run.py. In fact, when running as a module, Python executes an import on run.py, so print(sys.path) is executed successfully, and 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 this is python -m run.

4.2 What __main__.py does

Still looking at the example, suppose we have the following package:

Package ├ ─ ─ just set py └ ─ ─ __main__. Py123Copy the code

Where, the contents of the __init__.py file

import sys

print("__init__")
print(sys.path)1234
Copy the code

Where, the contents of the __main__.py file

import sys

print("__main__")
print(sys.path)1234
Copy the code

Next, we run the package, using python -m package, and output:

__init__ ['', ...]  __main__ ['', ...] 12345Copy the code

Run with python package and output:

__main__ ['package', ...] 12Copy the code

To summarize

  • When the -m argument is added, Python adds the current working directory to sys.path; Without -m, Python adds the script’s directory to sys.path.

  • When the -m argument is added, Python imports the module or package first and then executes it.

  • The __main__.py file is a package or directory entry program. The __main__.py file is always executed whether it is run with Python package or python -m package.

5. Refer to the article

1. If in Pythonname= = ‘main‘How to understand