停止讀取 Python 中的進程輸出而不掛起?
問題:
Python 程式需要與外部互動連續產生輸出的過程(例如「上」)。但是,直接讀取輸出可能會導致程式無限期掛起。
解決方案:
為了防止掛起,必須在以下情況下採用非阻塞或非同步機制:讀取過程輸出。以下是一些可能的方法:
假脫機暫存檔案(建議)
此方法利用專用檔案物件來儲存進程輸出。
#! /usr/bin/env python<br>導入子程序<br>導入臨時檔案<br>導入時間<p>def main():</p><pre class="brush:php;toolbar:false"># Open a temporary file (automatically deleted on closure) f = tempfile.TemporaryFile() # Start the process and redirect stdout to the file p = subprocess.Popen(["top"], stdout=f) # Wait for a specified duration time.sleep(2) # Kill the process p.terminate() p.wait() # Rewind and read the captured output from the file f.seek(0) output = f.read() # Print the output print(output) f.close()
if 名稱 == "__main__":
main()
基於執行緒的輸出讀取
這種方法採用單獨的執行緒來連續讀取進程輸出,同時主執行緒繼續執行其他任務。
導入集合<br>導入子程序<br>導入執行緒<br>導入時間<p>def read_output(process,append):</p><pre class="brush:php;toolbar:false">for line in iter(process.stdout.readline, ""): append(line)def main():
# Start the process and redirect stdout process = subprocess.Popen(["top"], stdout=subprocess.PIPE, close_fds=True) # Create a thread for output reading q = collections.deque(maxlen=200) t = threading.Thread(target=read_output, args=(process, q.append)) t.daemon = True t.start() # Wait for the specified duration time.sleep(2) # Print the saved output print(''.join(q))
if 名稱
== "__main__":main()
al.alarm ()(僅限Unix)
導入集合<pre class="brush:php;toolbar:false">pass導入訊號
導入子程序
raise Alarmclass Alarm(Exception):
# Start the process and redirect stdout process = subprocess.Popen(["top"], stdout=subprocess.PIPE, close_fds=True) # Set signal handler signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(2) try: # Read and save a specified number of lines q = collections.deque(maxlen=200) for line in iter(process.stdout.readline, ""): q.append(line) signal.alarm(0) # Cancel alarm except Alarm: process.terminate() finally: # Print the saved output print(''.join(q))def Alarm_handler(signum,🎜>
def Alarm_handler(signum,,) :
main()def main():
if
名稱== "__main__":
== "__main__":
# Start the process and redirect stdout process = subprocess.Popen(["top"], stdout=subprocess.PIPE, close_fds=True) # Create a timer for process termination timer = threading.Timer(2, process.terminate) timer.start() # Read and save a specified number of lines q = collections.deque(maxlen=200) for line in iter(process.stdout.readline, ""): q.append(line) timer.cancel() # Print the saved output print(''.join(q))threading.Timer
此方法使用計時器在指定的逾時後終止程序。它適用於 Unix 和 Windows 系統。
導入集合<pre class="brush:php;toolbar:false">main()導入子程序
導入執行緒
def main():
ifname
if
args = sys.argv[1:] if not args: args = ['top'] # Start the process and redirect stdout process = subprocess.Popen(args, stdout=subprocess.PIPE, close_fds=True) # Save a specified number of lines q = collections.deque(maxlen=200) # Set a timeout duration timeout = 2 now = start = time.time() while (now - start) if <p>name<strong></strong></p>if <pre class="brush:php;toolbar:false">main()name
if name
if 名稱 == "__main__":沒有線程,沒有訊號此方法使用簡單的基於時間的循環,用於檢查進程輸出,如果超過指定逾時則將其終止。導入集合導入子程序導入系統導入時間 def main():if 名稱 == "__main__":注意:儲存的行數可以依照需要透過設定deque資料結構的'maxlen'參數來調整。
以上是如何避免 Python 程式在讀取進程輸出時掛起?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

如何解決jieba分詞在景區評論分析中的問題?當我們在進行景區評論分析時,往往會使用jieba分詞工具來處理文�...

如何使用正則表達式匹配到第一個閉合標籤就停止?在處理HTML或其他標記語言時,常常需要使用正則表達式來�...


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)