首页  >  文章  >  后端开发  >  如何防止 Python 在从不断更新的进程中读取输出时冻结?

如何防止 Python 在从不断更新的进程中读取输出时冻结?

DDD
DDD原创
2024-10-28 08:44:30731浏览

How to Prevent Python from Freezing When Reading Output from a Constantly Updating Process?

停止读取 Python 中的进程输出而不挂起

尝试在 Python 中读取不断更新进程的输出时,可能会遇到冻结问题。这个问题特别在使用 readlines() 方法时出现。

问题:使用 readlines() 时冻结

在提供的代码片段中,进程 = os.popen("top")。 readlines() 行导致程序挂起。这是因为 readlines() 会立即读取子进程的整个输出,这可能会很大并导致长时间的阻塞操作。

使用 subprocess.Popen()

更好的方法是使用 subprocess.Popen() 函数创建子进程并管理其输入和输出。具体操作方法如下:

<code class="python">import subprocess

process = subprocess.Popen('top')
time.sleep(2)
os.popen("killall top")
print process</code>

此代码使用 Popen() 创建一个运行 top 的子进程。等待2秒后,终止顶层进程,最后打印子进程对象。然而,这种方法仍然返回一个未格式化的对象。

使用临时文件的解决方案

要在不阻塞程序的情况下读取子进程的输出,可以使用临时文件来存储输出。这是代码的改进版本:

<code class="python">#!/usr/bin/env python
import subprocess
import tempfile
import time

def main():
    # Create a temporary file to store the subprocess output
    f = tempfile.TemporaryFile()

    # Start the subprocess and redirect its stdout to the temporary file
    process = subprocess.Popen(["top"], stdout=f)

    # Wait for a few seconds
    time.sleep(2)

    # Kill the subprocess
    process.terminate()
    process.wait()

    # Seek to the start of the temporary file and read the output
    f.seek(0)
    output = f.read()

    # Close the temporary file
    f.close()

    # Print the output of the subprocess
    print(output)

if __name__=="__main__":
    main()</code>

此解决方案可确保程序在读取子进程的输出时不会挂起。 subprocess.wait() 方法等待子进程终止,确保在访问文件之前所有输出都已写入文件。

以上是如何防止 Python 在从不断更新的进程中读取输出时冻结?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn