在 Python 中停止進程輸出時如何避免 Readline 掛起?

Patricia Arquette
發布: 2024-10-30 08:44:02
原創
276 人瀏覽過

How to Avoid Readline Hangs When Stopping Process Output in Python?

在Python 中停止進程輸出時避免Readline 掛起

問題描述:

在使用os.popen 的使用os. Python 程式中() 或subprocess.Popen() 來讀取連續更新進程的輸出(例如top),當嘗試使用readlines() 讀取所有行時,程式可能會掛起。

解決方案:

使用臨時檔案和子程序:

<code class="python">import subprocess
import tempfile
import time

def main():
    # Open a temporary file for process output
    with tempfile.TemporaryFile() as f:
        # Start the process and redirect its stdout to the file
        process = subprocess.Popen(["top"], stdout=f)

        # Wait for a specified amount of time
        time.sleep(2)

        # Kill the process
        process.terminate()
        process.wait()  # Wait for the process to terminate to ensure complete output

        # Seek to the beginning of the file and print its contents
        f.seek(0)
        print(f.read())

if __name__ == "__main__":
    main()</code>
登入後複製

這種方法使用臨時檔案來儲存進程輸出,允許程式避免在readlines() 上阻塞。

替代解決方案:

將佇列與另一個執行緒一起使用:

<code class="python">import collections
import subprocess
import threading

def main():
    # Create a queue to store process output
    q = collections.deque()

    # Start the process and redirect its stdout to a thread
    process = subprocess.Popen(["top"], stdout=subprocess.PIPE)
    t = threading.Thread(target=process.stdout.readline, args=(q.append,))
    t.daemon = True
    t.start()

    # Wait for a specified amount of time
    time.sleep(2)

    # Terminate the process
    process.terminate()
    t.join()  # Wait for the thread to finish

    # Print the stored output
    print(''.join(q))

if __name__ == "__main__":
    main()</code>
登入後複製

使用signal.alarm():

<code class="python">import collections
import signal
import subprocess

class Alarm(Exception):
    pass

def alarm_handler(signum, frame):
    raise Alarm

def main():
    # Create a queue to store process output
    q = collections.deque()

    # Register a signal handler to handle alarm
    signal.signal(signal.SIGALRM, alarm_handler)

    # Start the process and redirect its stdout
    process = subprocess.Popen(["top"], stdout=subprocess.PIPE)

    # Set an alarm to terminate the process after a specified amount of time
    signal.alarm(2)

    # Read lines until the alarm is raised or the process terminates
    try:
        while True:
            line = process.stdout.readline()
            if not line:
                break
            q.append(line)
    except Alarm:
        process.terminate()

    # Cancel the alarm if it hasn't already fired
    signal.alarm(0)

    # Wait for the process to finish
    process.wait()

    # Print the stored output
    print(''.join(q))

if __name__ == "__main__":
    main()</code>
登入後複製

這些替代方案允許程式在保存進程輸出的同時繼續運作。它們可能更適合您需要持續監控流程輸出的情況。

以上是在 Python 中停止進程輸出時如何避免 Readline 掛起?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!