首頁 >後端開發 >Python教學 >如何從另一個 Python 腳本執行一個 Python 腳本,尤其是當一個 Python 腳本是一項服務時?

如何從另一個 Python 腳本執行一個 Python 腳本,尤其是當一個 Python 腳本是一項服務時?

DDD
DDD原創
2024-12-19 01:08:10390瀏覽

How Can I Execute One Python Script from Another, Especially When One is a Service?

從另一個腳本呼叫一個腳本

問題:

如何執行一個腳本來自另一個名為“service.py”的腳本,該腳本名為“test1.py”,該腳本作為服務?

答案:

要從另一個腳本呼叫一個腳本,通常採用以下方法使用:

test1.py:

def some_func():
    print('in test 1, unproductive')

if __name__ == '__main__':
    # test1.py executed as script
    # do something
    some_func()

service.py:

import test1

def service_func():
    print('service func')

if __name__ == '__main__':
    # service.py executed as script
    # do something
    service_func()
    test1.some_func()

此方法包括執行以下步驟:

  1. 定義一個test1.py中的函數: 在“test1.py”中建立一個函數,例如“some_func()”,封裝要執行的程式碼。
  2. 在服務中呼叫函數。 py: 在「service.py」中,導入「test1.py」並從「service_func()」中呼叫「some_func()」函數函數。
  3. 每個腳本的入口點: 確保「if name == '__main__'」條件在「test1.py」和「 service.py」來區分腳本是作為腳本本身運行還是由其他腳本導入。

以上是如何從另一個 Python 腳本執行一個 Python 腳本,尤其是當一個 Python 腳本是一項服務時?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn