# hello.py def SayHello (): str="hello" Print (str); if __name__ " __main__ " : Print ('This ismain of module ' hello.py') SayHello ()
When the module is executed separately, such as performing the above Hello.py:python hello.py alone, the output
This is main of the module "hello.py" Hello
It can be understood that the phrase "if __name__==" __main__ ":" is consistent with the main () function in C, that is, as a portal
When the module is introduced into use by another module, the block represented by "if __name__==" __main__ ":" is not executed because the value of its __name__ is changed when the module is referenced by another module, __ The value of the name__ will be the name of the module. For example, after you import the hello in the Python shell, look at hello.__name__:
>>> import hello>>> hello.__name__ ' Hello ' >>>
There is a sentence that summarizes the meaning of this code: "Makea 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.
Run the. py file directly in cmd, then the value of __name__ is ' __main__ ';
After import a. py file, the value of __name__ is not ' __main__ ';
Use if __name__ = = ' __main__ ' to determine if the. py file is running directly
This allows the "module" file to be run or introduced by other modules without executing the function 2 times.
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!
The role of __name__ = ' __main__ ' in Python