為了在后臺運行子行程而不干擾主代碼的連續性,我這樣呼叫 Python 檔案:
Popen(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
有什么方法可以使用此呼叫運行第一個檔案('secondary.py'),然后'tertiary.py'在完成該程序時運行另一個檔案()?
例如:
Popen(['secondary.py','tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
筆記:
我不能這樣稱呼一個低于另一個:
Popen(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
Popen(['tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
因為它們將成為兩個獨立的子流程,這不是我的預期目標,所以我需要完成一個然后運行另一個。
uj5u.com熱心網友回復:
subprocess.run等到命令完成。您可以創建一個后臺執行緒來連續運行您想要的所有命令。
import threading
import subprocess
def run_background():
subprocess.run(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
subprocess.run(['tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
bg_thread = threading.Thread(target=run_background)
bg_thread.start()
因為這沒有被標記為守護執行緒,所以主執行緒將等到該執行緒完成并退出程式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476534.html
