簡體   English   中英

如何根據特定條件終止以 subprocess.Popen() 開頭的腳本

[英]How to terminate the script started with subprocess.Popen() based on specific condition

我正在從名為 main.py 的主腳本開始一個名為test.pymain.py腳本。 test.py中,我正在跟蹤一些機器學習指標。 當這些指標達到某個閾值時,我想終止啟動test.py的子進程。

如果我使用以下方法啟動此腳本,是否有可能在 Python 中實現此目的:
proc = subprocess.Popen("python test.py", shell=True)

我在文檔中沒有找到任何可以讓我自己觸發此事件的內容。

您可以從stdoutstdin使用打印和讀取。 例如,考慮一個簡單的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM