使用python捕获进程输出的最佳方法是什么?

 手机用户2502858341 发布于 2023-02-03 09:39

我正在使用python的subprocess模块来启动一个新进程.我想实时捕获新进程的输出,以便我可以用它做事(显示它,解析它等).我已经看到很多关于如何做到这一点的例子,一些使用自定义文件类对象,一些使用threading,一些尝试读取输出直到进程完成.

文件对象示例(单击我)

我宁愿不使用自定义类文件的对象,因为我想允许用户为提供自己的价值观stdin,stdoutstderr.

线程示例(点击我)

我真的不明白为什么需要线程,所以我不愿意遵循这个例子.如果有人可以解释为什么线程示例有意义我会很高兴听.但是,此示例还限制用户提供自己的值stdoutstderr值.

读取输出示例(见下文)

对我来说最有意义的例子是阅读stdout,stderr直到过程结束.这是一些示例代码:

import subprocess

# Start a process which prints the options to the python program.
process = subprocess.Popen(
    ["python", "-h"],
    bufsize=1,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
)    

# While the process is running, display the output to the user.
while True:

    # Read standard output data.
    for stdout_line in iter(process.stdout.readline, ""):

        # Display standard output data.
        sys.stdout.write(stdout_line)

    # Read standard error data.
    for stderr_line in iter(process.stderr.readline, ""):

        # Display standard error data.
        sys.stderr.write(stderr_line)

    # If the process is complete - exit loop.
    if process.poll() != None:
        break

我的问题是,

问:是否有建议的方法使用python捕获进程的输出?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有