In most well-orchestrated scripts or programs there is this if __name__ = = ' main ':, although always aware of his role, but has been relatively vague, the collection of information in detail after the fight to share.
1, the function of this piece of code
A python file has two methods to use, the first is to execute directly as a script, and the second is import into other Python scripts called (module reuse) execution. So if __name__ = = ' main ': The function is to control the process of executing the code in both cases, the IF __name__ = = ' main ': code under the first case (that is, the file is executed directly as a script) will be executed, Import into other scripts will not be executed.
As an example, the following code is written in test.py:
Print "I ' m the first." If __name__== "__main__": print "I ' m the second."
and execute test.py directly, as a result, you can print two lines of string successfully. That is, if __name__== "__main__": the code before and after the statement is executed.
Then create a new script with the name import_test.py in the same folder, just enter the code as follows:
Import Test
Execute the import_test.py script with the following output:
Only the first line of string is printed. That is, if __name__== "__main__": The previous statement was executed and then not executed.
2, the principle of operation
Each Python module (python file, test.py and import_test.py here) contains the built-in variable __name__, and when the runtime module is executed, __name__ equals the file name (contains the suffix. py); If import is in another module, __name__ equals the module name (without the suffix. py). and "__main__" equals the name of the current execution file (with the suffix. py). Then, when the module is executed directly, the __NAME__ = = ' Main ' result is true.
As an example, we test.py the __name__== "__main__" in the script if it was previously added to print __name__ and will be printed __name__. The contents and results of the file are as follows
It can be seen that the value of the variable __name__ is "__main__";
Then execute the import_test.py, the module content and execution results are as follows:
At this point, the value of the __name__ variable in test.py is test and does not meet the __name__== "__main__" condition, so the subsequent code cannot be executed.
if __name__ = = ' main ' in Python programming: Functions and principles