Function of _ name _ = '_ main _' in python, __name ___ main __
Python ScriptIt is a widely used batch automatic processing solution, and any. py extension file can be used as a Module file in the Python execution program. From the design philosophy that everything in Python is an object, we can use some built-in Python methods after importing the. py extension file into the Python execution program.
# Hello. pydef sayHello (): str = "hello" print (str); if _ name _ = "_ main __": # main program entry print ('this is main of module "hello. py "') sayHello ()
When the module is executed separately, for example, if the preceding hello. py: python hello. py is executed separately, the output
This is main of module "hello.py"hello
It can be understood as "if _ name __= =" _ main _ ":" This sentence is consistent with that expressed by the main () function in c.
When this module is introduced and used by other modules, the Block indicated by "if _ name __= =" _ main _ ":" is not executed, this is because when the module is referenced by other modules, the value of _ name _ will change, and the value of __name _ will be the name of the module. For example, after importing hello in python shell, view hello. _ name __:
>>> import hello>>> hello.__name__'hello'>>>
Here is a classic summary of the significance of this Code: "Make a script both importable and executable"
This means that the script module you write can be imported to other modules, and the module can also be executed by yourself.
Run the. py file directly in cmd, and the value of _ name _ is '_ main __';
After importing a. py file, the value of __name _ Is Not '_ main;
Use if _ name _ = '_ main _' to determine whether the. py file is directly running.
In this way, the "module" file can be run, introduced by other modules, and the function is not executed twice.
Summary:
If we directly execute. in The py file, "_ name _ = '_ main _'" is True,. when the py file is imported through import, the value of _ name _ is the name of the py file instead of _ main __.
This function is also useful: When debugging code, add some of our debugging code in "if _ name _ = '_ main, we can prevent external modules from executing our debugging code when calling the Code. However, if we want to troubleshoot the problem, we can directly execute the module File to run the debugging code normally!