在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中文網其他相關文章!

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

文章討論了虛擬環境在Python中的作用,重點是管理項目依賴性並避免衝突。它詳細介紹了他們在改善項目管理和減少依賴問題方面的創建,激活和利益。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

記事本++7.3.1
好用且免費的程式碼編輯器

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中