Many beginners just start to learn python often see python in __name__ = \ ' __main__\ ' such code, may be a lot of novice start learning at the time are more confused, python __name__ = ' __main__ ' role, What are you doing?
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 .
The __name__ is the current module name, and the module is named __main__ when the module is run directly. This means that when the module is run directly, the following code block will be run and the code block is not run when the module is imported.
This sentence, may start to listen to not very understand. The following examples illustrate:
Write a module first:
?
| 12345 |
#module.py defmain(): print "we are in %s"%__name__ if __name__ ==‘__main__‘: main() |
This function defines a main function, and we execute the PY file to find that the result is to print out "We is in __main__", stating that the contents of our if statement are executed, calling main ():
But what if we import the module from another module and call the main () function once?
?
| 123 |
#anothermodle.py frommodule importmain main() |
The result of its execution is: we is in module
However, "We is in __main__" is not shown, which means that the function under module __name__ = ' __main__ ' is not executed.
This allows the "module" file to be run or introduced by other modules without executing the function 2 times. That's the point.
To summarize:
If we are directly executing a. py file, the file then "__name__ = = ' __main__ '" is true, but if we import the file through import from another. py file, then __name__ The value is the name of our py file, not the __main__.
This feature 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!
A brief analysis of the role of __name__ = ' __main__ ' in Python