連続プロセス出力を読み取るときに Python プログラムがハングしないようにするにはどうすればよいですか?
Python でのハングなしのプロセス出力読み取りの停止
バックグラウンド
連続出力を生成するツールで Python の os.popen() 関数を使用する場合、出力を読み取ろうとすると、プログラムが頻繁にハングします。
os.popen()問題
問題のある行 process = os.popen("top").readlines() は、プロセス出力全体を一度に読み取ろうとする readlines() によりプログラムを停止させます。
subprocess.Popen() による解決策
この問題を解決するには、os.popen() の代わりに subprocess.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>
この修正されたコード:
- readlines() の代わりに communication() を使用してプロセス出力を変数にキャプチャします。
- kill シグナルを「トップ」プロセスに送信します。
- のファイルの終わりを宣言します。
テールのようなアプローチ
プロセスの出力の一部だけが必要な場合は、テールのようなソリューションを使用してキャプチャできます。特定の行数。
スレッドベースのアプローチ
別のスレッドでプロセス出力をキャプチャするには、以下:
<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 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











fiddlereveryversings for the-middleの測定値を使用するときに検出されないようにする方法

10時間以内にコンピューター初心者プログラミングの基本を教える方法は?コンピューター初心者にプログラミングの知識を教えるのに10時間しかない場合、何を教えることを選びますか...

Investing.comの反クラウリング戦略を理解する多くの人々は、Investing.com(https://cn.investing.com/news/latest-news)からのニュースデータをクロールしようとします。

Pythonasyncioについて...

SCAPYクローラーを使用するときにパイプラインファイルを作成できない理由についての議論は、SCAPYクローラーを学習して永続的なデータストレージに使用するときに、パイプラインファイルに遭遇する可能性があります...

Python 3.6のピクルスファイルの読み込みエラー:modulenotfounderror:nomodulenamed ...
