_ Name __:
When using itself, it is main, for example, you execute:
Python test. py
The name in test. py is main.
If you import test in test2, then name is the file name http://www.cnblogs.com/herbert/archive/2011/09/27/2193482.html
I have seen many python codes with this code:
If _ name _ = '_ main _': The main function of this Code is to allow the python file to run independently, it can also be imported to other files as a module. When importing to other script files, the main code will not be executed. Reference: http://pyfaq.infogami.com/tutor-what-is-if-name-main-for The if _ name _ = "_ main __":... trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. as a toy example, let's say that we have two files:
Mumak :~ Dyoo $ cat mymath. py
Def square (x ):
Return x * x
If _ name _ = '_ main __':
Print "test: square (42) =", square (42)
Mumak :~ Dyoo $ cat mygame. py
Import mymath
Print "this is mygame ."
Print mymath. square (17) In this example, we 've written mymath. py to be both used as a utility module, as well as a standalone program. we can run mymath standalone by doing this:
Mumak :~ Dyoo $ python mymath. py
Test: square (42) = 1764But we can also use mymath. py as a module; let's see what happens when we run mygame. py:
Mumak :~ Dyoo $ python mygame. py
This is mygame.
289 Notice that here we don't see the 'test' line that mymath. py had near the bottom of its code. that's because, in this context, mymath is not the main program. that's what the if _ name _ = "_ main __":... trick is used.
In this example, when the square function is called in mygame. py, the main function in mymath. py is not executed.