關於Python中的 if __name__ == '__main__'

來源:互聯網
上載者:User

標籤: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__'

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.