In Python we'll see a piece of code like this:
1 if __name__= ='__main__': 2 main ()
What does this code mean, we can know that the code means that if __name__== ' __main__ ' is ture, then the main () function is called
There is a phrase that sums up the meaning of this code in a classic way:
"Make a script both importable and executable"
It means that the script module that you write can be imported into other modules, and the module can be executed by itself .
what is the value of __name__? the module is an object, and all modules have a built-in property of __name__. The value of the __name__ of a module depends on how you apply the module. If you import a module, the value of the module __name__ is usually the module file name, without the path or file extension. But you can also run the module directly like a standard program, in which case the __name__ value will be a special default "__main__".
We use examples to illustrate:
1 # module.py 2 def Main (): 3 Print " we is in%s "%__name__4if__name__'__main__ ' : 5 Main ()
This module defines a main () function, and the result of the operation is to print out "We is in __main__", stating that the main () function in our code module is called and executed, there is an if code, the module can execute itself, and __name__== ' __main_ _‘
But what if we import the module from another module and call the main () function once?
1 # anothermodle.py 2 from Import Main 3 Main ()
The result of its execution is: we is in module
This means that our __name__== ' module ', which is the module file name of the module where main ()
This is the key for both the "module" file to run and the other modules to be introduced.
Summarize:
(1) If we are directly executing a. py file, the file then "__name__ = = ' __main__ '" is true, but if we import the file from another. py file through import and call the function in this file, this is the function The value of __name__ is the name of our py file, not the __main__.
With this piece of code:
1 if __name__ ' __main__ ' : 2 ' debug code '
(2) This function also has a use: When debugging code, in "if __name__ = = ' __main__ '" to add some of our debugging code, we can let the external module calls do not execute our debugging code, but if we want to troubleshoot the problem, directly execute the module file, Debug your code to work!
If __name__== ' __main__ ': Main () parsing in Python