首頁  >  文章  >  後端開發  >  如何防止 Python 在從不斷更新的進程中讀取輸出時凍結?

如何防止 Python 在從不斷更新的進程中讀取輸出時凍結?

DDD
DDD原創
2024-10-28 08:44:30731瀏覽

How to Prevent Python from Freezing When Reading Output from a Constantly Updating Process?

停止讀取 Python 中的進程輸出而不掛起

嘗試在 Python 中讀取不斷更新進程的輸出時,可能會遇到凍結問題。這個問題特別在使用 readlines() 方法時出現。

問題:使用 readlines() 時凍結

在提供的程式碼片段中,進程 = os.popen("top")。 readlines() 行導致程式掛起。這是因為 readlines() 會立即讀取子程序的整個輸出,這可能會很大並導致長時間的阻塞操作。

使用 subprocess.Popen()

更好的方法是使用 subprocess.Popen() 函數建立子程序並管理其輸入和輸出。具體操作方法如下:

<code class="python">import subprocess

process = subprocess.Popen('top')
time.sleep(2)
os.popen("killall top")
print process</code>

此程式碼使用 Popen() 建立一個運行 top 的子程序。等待2秒後,終止頂層進程,最後列印子進程物件。然而,這種方法仍然傳回一個未格式化的物件。

使用暫存檔案的解決方案

要在不阻塞程式的情況下讀取子程序的輸出,可以使用暫存檔案來儲存輸出。這是程式碼的改進版本:

<code class="python">#!/usr/bin/env python
import subprocess
import tempfile
import time

def main():
    # Create a temporary file to store the subprocess output
    f = tempfile.TemporaryFile()

    # Start the subprocess and redirect its stdout to the temporary file
    process = subprocess.Popen(["top"], stdout=f)

    # Wait for a few seconds
    time.sleep(2)

    # Kill the subprocess
    process.terminate()
    process.wait()

    # Seek to the start of the temporary file and read the output
    f.seek(0)
    output = f.read()

    # Close the temporary file
    f.close()

    # Print the output of the subprocess
    print(output)

if __name__=="__main__":
    main()</code>

此解決方案可確保程式在讀取子程序的輸出時不會掛起。 subprocess.wait() 方法等待子程序終止,確保在存取檔案之前所有輸出都已寫入檔案。

以上是如何防止 Python 在從不斷更新的進程中讀取輸出時凍結?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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