The role and principle of if __name__ == 'main': in python programming

The role and principle of if __name__ == 'main': in python programming

In most well-arranged scripts or programs, there is this if __name__ == 'main': . Although I have always known its function, it has always been vague. After collecting data and understanding it in detail, I will share it with the fight.

1. The function of this code

There are two ways to use a python file, the first is to execute it directly as a script, and the second is to import it into other python scripts to be called (module reuse) for execution.

if __name__ == 'main': is to control the execution process of the code in these two cases, the code under if __name__ == 'main': will only be executed in the first case (that is, the file is directly executed as a script) Executed, and imports into other scripts will not be executed.

  For example, write the following code in test.py:

1 print "I'm the first."
2 if __name__=="__main__":
3      print "I'm the second."

And directly execute test.py , the result is as shown below, you can successfully print two lines of strings. That is, the code before and after the if __name__=="__main__": statement is executed .

python script test


Then create a new script named import_test.py in the same folder, and only enter the code such as:

import test
executes the import_test.py script, and the output is as follows:
 
if __name__=="__main__"演示

Only the first line of string is output. That is, if __name__=="__main__": the statement before is executed, and the statement after it is not executed . 


2. The principle of operation

__name__ is included in both test.py and import_test.py files .

When run directly as a script (test.py), __name__ is equal to the file name, and the value of __name__ is main (including the suffix .py). At this point , the code before and after if __name__=="__main__" can be run .

Import into other python scripts to be called (module reuse) runtime (import__test.py), __name__ is equal to the module name, and the value of __name__ is main (excluding the suffix .py). At this time, only the words in front of if __name__=="__main__" can run, and the following words cannot run.

3. Examples

We add print __name__ before if __name__=="__main__": in the test.py script , that is, print out __name__. The file content and results are as follows,

python script

  It can be seen that the value of the variable __name__ is "__main__" at this time;
  then execute import_test.py, the module content and execution results are as follows:

 __name__ variable

  At this point, the value of the __name__ variable in test.py is test, which does not satisfy the condition of __name__=="__main__", therefore, the following code cannot be executed.


Reprinted from: http://www.dengfeilong.com/post/60.html (with some modifications)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324735243&siteId=291194637