如何在 Python 中获取子进程的实时输出?

Patricia Arquette
发布: 2024-11-15 13:46:02
原创
846 人浏览过

How to Get Realtime Output from a Subprocess in Python?

Realtime Output from Subprocess

When executing command line programs using Python's subprocess module, developers often encounter the issue of buffered output. This can be problematic for tasks that require line-by-line processing.

To resolve this issue, users can consider the following approach:

  • Utilize p.stdout.readline() within a while loop to read each line of output as soon as it becomes available. For example:
while True:
    line = p.stdout.readline()
    if not line: break  # No more output, exit loop

    # Process the current line as needed...
登录后复制

This method allows for real-time output processing without encountering buffering issues. Despite initial attempts with for line in p.stdout: and bufsize settings, this approach has been proven to effectively capture output in a timely manner.

以上是如何在 Python 中获取子进程的实时输出?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板