我subprocess.run()用來運行一個包含 python 代碼的 .txt 檔案。該 python 代碼可能包含一個 while 回圈。我需要我的其余代碼在運行時運行。這樣做的明顯方法是使用 threading模塊,當我放入subprocess.run()一個單獨的執行緒時,它會回傳類似Enable tracemalloc to see traceback(錯誤)或類似的東西。
#.txt file
while True:
print("Hello")
#.py file:
import subprocess
import threading as th
def thread():
subprocess.run('python foo.txt')
th2=th.Thread(target=thread)
th2.start()
#code here
uj5u.com熱心網友回復:
您根本不需要執行緒,因為子行程是一個單獨的行程。
但是,您確實需要從阻塞.run()便利功能切換到Popen:
import subprocess
import sys
import time
proc = subprocess.Popen([sys.executable, 'foo.txt'])
# ... do other things here...
time.sleep(1)
proc.kill()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513751.html
