Python Empire (ID:PYTHONDG)
Difficulty: Beginner
Demo Environment:
Os:ubuntu 16.04
python:3.6
We often see the following statement when writing Python code. It seems to be the Main function of Python. What does it mean exactly?
if __name__ = = ' __main__ ': print (' Hello World ')
First Python has two concepts, source files :
~/code_house/py_dev$ tree.├──file1.py├──file2.py└──p_main.py
The contents are:
py_main.py
Import File1import file2if __name__ = = ' __main__ ': print (file1) print (file2) print (file1.__name__) print (file2 . __name__) Print (__name__) #py_main
Both file1.py and file2.py are empty, and then look at the effect of the operation:
~/code_house/py_dev$ python3 p_main.py <module ' file1 ' from '/home/xinwen/code_house/py_dev/file1.py ' >< Module ' file2 ' from '/home/xinwen/code_house/py_dev/file2.py ' >file1file2__main__
You can see the import of the file printed results are no longer a file but module
Print (file1): <module ' file1 ' from '/home/xinwen/code_house/py_dev/file1.py ' >print (file2): <module ' file2 ' From '/home/xinwen/code_house/py_dev/file2.py ' >
This is the form in which the Python source file is loaded into memory, and it exists in the form of a Python module.
and the name of the **module * * is also the name of the Python source code file:
Print (file1.__name__) file1print (file2.__name__) file2
Typically, the module name in memory is the corresponding file name. But one situation is different, when the file is used as a startup file, or the first file that is executed, the name of the module in memory generated by the file is no longer its file name:
Print (__name__) #py_main__main__
Unity is main .
This article from the "front-end people's Python Empire" blog, reproduced please contact the author!
How do I understand the main function of Python?