python, IF name == ' main ': the role and principles
Find useful, welcome to discuss mutual learning together - Follow Me
A python files typically used in two ways, first as a script is executed directly, and the second is to import another python script is called (block reuse) performed. Thus IF name == 'main': the role of these two cases is to control execution of the code of the process, the IF name == 'main': under the code only (i.e., as a script file direct execution) only in the first case It will be executed, and import to other scripts will not be executed. Examples are as follows:
- Direct execution
direct executiontest.py
results as shown below, can successfully print two lines of character strings. That is, IF name == " main ": the code before and after the statements are executed.
- import performed
then the new folder name in the same script file import_test.py, enter the following code:
execution import_test.py script, the following output:
output only the first line of the character string. That is, IF name == " main ": before the statement is executed, not executed after.
the reason
- This is because each file has a
__name__
variable, in test.py file, if executed directly,__name__
that is test.py, if the implementation is the test in another file. - And each file has a
__main__
constant, this constant value at all times to test.py, namely the file name + .py - Further when the module is executed directly, name == 'main' is true.
To further illustrate, we intest.py
if the script name == " main ": Prior to joining Print ( name ), is about to name printed. File contents and results are as follows:
As can be seen, when the value of the variable __name__ " main ."
Then execute import_test.py, execution results are as follows:
At this time, in the test.py Test __name__ variable value, does not satisfy name == " main condition", therefore, can not execute the subsequent code.