標籤:nal https set bsp col lib anon == cond
官方文檔對於"__main__"的回答(ref: https://docs.python.org/2/library/__main__.html):
This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:
if __name__ == "__main__": main()
也就是說,當解譯器的主專案執行的時候,使用__main__來指示代碼的執行範圍。執行主專案的命令可以來自標準輸入(python xxx.py),指令檔等
stackoverflow的回答如下(ref:https://stackoverflow.com/questions/419163/what-does-if-name-main-do):
對於__name__的解釋:
For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module‘s name.
為什麼要這樣設計的原因:
One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
關於Python中的 if __name__ == '__main__'