看過很多python的code都有這段代碼:
if __name__ == '__main__':
這段代碼的主要作用主要是讓該python檔案既可以獨立運行,也可以當做模組匯入到其他檔案。當匯入到其他的指令檔的時候,該main代碼裡面的就不執行了。
參考:
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.pydef square(x): return x * xif __name__ == '__main__': print "test: square(42) ==", square(42)mumak:~ dyoo$ cat mygame.pyimport mymathprint "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.pytest: square(42) == 1764
But we can also use mymath.py as a module; let's see what happens when we run mygame.py:
mumak:~ dyoo$ python mygame.pythis 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 for.
在這個例子裡面mygame.py裡面調用square函數的時候,就不會執行mymath.py裡面的main函數了。