Python中if __name__ == "__main__": 的作用 (整理轉自Arkenstone) --感謝!

來源:互聯網
上載者:User

標籤:ref   col   div   代碼   art   檔案的   else   port   bsp   

Python中if __name__ == "__main__": 的作用

在很多python指令碼中在最後的部分會執行一個判斷語句if __name__ == "__main__:",之後還可能會有一些執行語句。那添加這個判斷的目的何在?

在python編譯器讀取源檔案的時候會執行它找到的所有代碼,而在執行之前會根據當前啟動並執行模組是否為主程式而定義變數__name__的值為__main__還是模組名。因此,該判斷語句為真的時候,說明當前啟動並執行指令碼為主程式,而非主程式所引用的一個模組。這在當你想要運行一些只有在將模組當做程式運行時而非當做模組引用時才執行的命令,只要將它們放到if __name__ == "__main__:"判斷語句之後就可以了。

具體舉個栗子方便理解:

# file one.pydef func():    print("func() in one.py")print("top-level in one.py")if __name__ == "__main__":    print("one.py is being run directly")else:    print("one.py is being imported into another module")
# file two.pyimport one        # start executing one.pyprint("top-level in two.py")one.func()if __name__ == "__main__":    print("two.py is being run directly")else:    print("two.py is being imported into another module")

 

運行 python one.py輸出如下:

top-level in one.pyone.py is being run directly

運行python two.py 輸出如下:

[email protected]:~/test$ python3 two.pytop-level in one.pyone.py is being imported into another moduletop-level in two.pyfunc() in one.pytwo.py is being run directly

 

Python中if __name__ == "__main__": 的作用 (整理轉自Arkenstone) --感謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.