[英]How to terminate the script started with subprocess.Popen() based on specific condition
我正在從名為 main.py 的主腳本開始一個名為test.py
的main.py
腳本。 在test.py
中,我正在跟蹤一些機器學習指標。 當這些指標達到某個閾值時,我想終止啟動test.py
的子進程。
如果我使用以下方法啟動此腳本,是否有可能在 Python 中實現此目的:
proc = subprocess.Popen("python test.py", shell=True)
我在文檔中沒有找到任何可以讓我自己觸發此事件的內容。
您可以從stdout
和stdin
使用打印和讀取。 例如,考慮一個簡單的test.py
計算(以一種非常低效的方式)一些素數:
測試.py
import time
primes = [2, 3]
if __name__ == "__main__":
for p in primes:
print(p, flush=True)
i = 5
while True:
for p in primes:
if i % p == 0:
break
if i % p:
primes.append(i)
print(i, flush=True)
i += 2
time.sleep(.005)
您可以閱讀 output 並選擇在達到所需的 output 時終止進程。 例如,我想得到最高1000
的素數。
import subprocess
proc = subprocess.Popen("python test.py",
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
bufsize=1, universal_newlines=True,
shell=True, text=True)
must_stop = False
primes = []
while proc.poll() is None:
line = proc.stdout.readline()
if line:
new_prime = int(line)
primes.append(new_prime)
if new_prime > 1000:
print("Threshold achieved", line)
proc.terminate()
else:
print("new prime:", new_prime)
print(primes)
請注意,由於處理和通信存在延遲,您可能會得到比預期多一兩個素數。 如果你想避免這種情況,你需要雙向通信,而test.py
會更復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.