問題描述:
在使用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中文網其他相關文章!