If _ name _ = & #39 ;__ main __& #39; how to correctly understand, __name ___ main __

Source: Internet
Author: User

If _ name _ = '_ main _' How to correctly understand, __name ___ main __
Preface:

In the eyes of friends, you are James (_ name _ = 'James '),
You are yourself (_ name _ = '_ main __'),

Your programming is very good. A friend calls you to help him write a program (import James, then you are in the eyes of a friend: _ name _ = 'xiaoming '),
But you will also open the xx website at night to do some of your own things (directly run Xiaoming. py, _ name _ = '_ main _').

For many programming languages, a program must have an entry, such as C, C ++, and fully object-oriented programming languages such as Java and C. If you have been familiar with these languages, you should have a good understanding of the concept of program entry. Both C and C ++ need a main function as the program entry, that is, the program runs from the main function. Similarly, Java and C # must have a Main class containing the Main method as the program entry.

Python, however, is different. It is a scripting language. It does not compile the program into binary before running it, but is a dynamic line-by-line interpretation operation. That is to say, there is no unified entry to run the script from the first line.

A Python source code file can be directly run and imported as a module (library. No matter whether it is imported or directly run, the top-level code will be run (Python uses indentation to differentiate the code hierarchy ). In fact, we do not want to run some code during import.

For example, suppose we have a const. py file with the following content:

PI = 3.14def main():    print "PI:", PImain()

  

We defined some constants in this file, and then wrote a main function to output the defined constants. Finally, running the main function is equivalent to performing a manual check on the definition, check whether the values are set correctly. Then we directly execute the file (python const. py) and output:

PI: 3.14

Now, we have an area. the py file is used to calculate the area of the circle, which must use const. the PI variable in the py file, then we start from const. in py, import the PI variable to area. in py:

from const import PIdef calc_round_area(radius):    return PI * (radius ** 2)def main():    print "round area: ", calc_round_area(2)main()

  

Run area. py. The output result is:

PI: 3.14round area:  12.56

As you can see, the main function in const is also run. In fact, we don't want it to be run. The main function is provided to test the definition of constants. At this time,if __name__ == '__main__'This is useful. Change const. py to the following:

PI = 3.14def main():    print "PI:", PIif __name__ == "__main__":    main()

  

Then run area. py and the output is as follows:

round area:  12.56

Run const. py and the output is as follows:

PI: 3.14

This is what we want.

if __name__ == '__main__'It is equivalent to Python.Simulated Program entry. Python itself does not stipulate such writing, which is just a coding habit. Because of the mutual reference between modules, different modules may have such definitions, and the entry program can only have one. Which portal program is selected depends on__name__.

_ Name __

__name__Is a built-in variable used to indicate the name of the current module and reflect the structure of a package. For example, assume that the following package is used:

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

  

The contents of all py files in the directory are:

print __name__

We executepython -c "import a.b.c", Output result:

aa.ba.b.c

  

As you can see,__name__It can clearly reflect the layers of a module in the package. In fact, the so-called Module name is the name required for import, for example:

import tornadoimport tornado.web

Tornado and tornado. web are called module names.

If a module is run directly, there is no package structure.__name__The value is__main__. For example, in the preceding example, run the c. py file (python a/B/c. py). The output result is as follows:

__main__

So,if __name__ == '__main__'Our simple understanding is:If the module is run directly, the code block is run. If the module is imported, the code block is not run..

In fact, this problem can also lead to other knowledge points, such__main__.pyFile and Python-mParameters.

_ Main _. py file and python-m

Python-mParameters are used to run a module or package as a script, while__main__.pyThe file is equivalent to the "Entry Program" of a package.

First, let's take a look.python xxx.pyAndpython -m xxx.py. The difference between the two methods of running Python programs is that one is to run directly, and the other is to run as a module.

Let's take a look at a simple example. assume there is a Python file run. py with the following content:

#!/user/bin/python#coding=utf-8import sysprint __name__print sys.path

 

Run python run. py directly to output the result. (to illustrate the problem, only the important part of the output is truncated, as shown in the following figure ):

__main__['/yh1', '/usr/lib/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old',
'/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/local/lib64/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages', '/usr/lib/python2.7/site-packages']

  

Run python-m run. py as a module ):

run['', '/usr/lib/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/local/lib64/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages', '/usr/lib/python2.7/site-packages']/usr/bin/python: No module named run.py

  

Then let's summarize:

  • 1,When the-m parameter is added, the current working directory is added to sys. path. If the parameter is not added, the directory where the script is located is added to sys. path..
  • 2,When the-m parameter is added, Python will first import the module or package, and then execute
  • 3,The _ main _. py file is a package or directory entry program.Whether it is usedpython packageStill usedpython -m packageDuring runtime, The __main _. py file is always executed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.