首頁  >  文章  >  後端開發  >  如何避免Python程式在讀取連續進程輸出時掛起?

如何避免Python程式在讀取連續進程輸出時掛起?

DDD
DDD原創
2024-11-01 09:47:02319瀏覽

How to Avoid Python Programs Hanging When Reading Continuous Process Output?

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

背景

當將Python 的os.popen() 函數與產生連續輸出的工具一起使用時,嘗試讀取輸出時程式經常掛起。

os.popen() 問題

有問題的行進程= os.popen("top").readlines() 由於以下原因暫停程式readlines(),它嘗試一次讀取整個進程的輸出。

使用 subprocess.Popen() 的解決方案

要解決此問題,請使用 subprocess.Popen() 而不是 os.popen ()。這是一個更正的範例:

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

# Start "top" process with stdout redirection
process = subprocess.Popen(["top"], stdout=subprocess.PIPE)

# Wait for 2 seconds
time.sleep(2)

# Send kill signal to "top" process
os.popen("killall top")

# Read process output
output, _ = process.communicate()
print(output.decode())</code>

此修改後的程式碼:

  • 使用 communications() 而不是 readlines() 擷取變數中的流程輸出。
  • 向「頂部」程序發送終止訊號。
  • 宣告進程 I/O 流的檔案結束並退出程式。

類似尾部的方法

如果只需要進程輸出的一部分,可以使用類似尾部的解決方案來捕獲特定數量的行。

基於執行緒的方法

擷取程式在單獨的執行緒中輸出,請嘗試以下操作:

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

# Start process with stdout redirection
process = subprocess.Popen(["top"], stdout=subprocess.PIPE)

# Define function to read process output in a thread
def read_output(process):
    for line in iter(process.stdout.readline, ""):
        ...  # Implement your logic here to process each line

# Create and start a thread for reading and processing output
reading_thread = threading.Thread(target=read_output, args=(process,))
reading_thread.start()

# Wait for 2 seconds, then terminate the process
time.sleep(2)
process.terminate()

# Wait for the reading thread to complete
reading_thread.join()</code>

signal.alarm() 方法

您也可以使用signal.alarm() 在指定逾時後終止進程:

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

# Define signal handler
def alarm_handler(signum, frame):
    # Raise an exception to terminate the process reading
    raise Exception

# Set signal handler and alarm for 2 seconds
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(2)

# Start process with stdout redirection
process = subprocess.Popen(["top"], stdout=subprocess.PIPE)

# Capture process output
number_of_lines = 200
q = collections.deque(maxlen=number_of_lines)
for line in iter(process.stdout.readline, ""):
    q.append(line)

# Cancel alarm
signal.alarm(0)

# Print captured output
print(''.join(q))</code>

threading.Timer 方法

或者,您可以使用threading.Timer 來安排進程終止:

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

# Define function to terminate the process
def terminate_process(process):
    process.terminate()

# Start process with stdout redirection
process = subprocess.Popen(["top"], stdout=subprocess.PIPE)

# Create and start a timer to terminate process in 2 seconds
timer = threading.Timer(2, terminate_process, [process])
timer.start()

# Capture process output
number_of_lines = 200
q = collections.deque(process.stdout, maxlen=number_of_lines)

# Cancel timer
timer.cancel()

# Print captured output
print(''.join(q))</code>

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

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