实时显示子进程输出 [英] Display subprocess output in real time

查看:42
本文介绍了实时显示子进程输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我在寡妇上使用 subporcess 库在 cmd 中执行命令.我的问题是我想实时显示 cmd 的输出.我能够在命令执行她的工作后显示输出.是否可以实时显示输出?

Curently I am using subporcess library on widows to execute comand in cmd. My problem is that I would like to display the output of cmd in the real time. I am able to display output after comand exececute her job. Is it possible to do display the output in real time?

我的代码如下所示:

import subprocess

def get_output(command):
    process = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    output = process.communicate()[0]
    return output.decode('utf-8')

print(get_output('ping 8.8.8.8'))

推荐答案

这对您有帮助吗?

  import subprocess
  import shlex

    def get_output(command):
        process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
        while True:
            output = process.stdout.readline()
            if output == '' and process.poll() is not None:
                break
            if output:
                print output.strip()
        rc = process.poll()
        return rc

您可能会发现有用的此链接.

这篇关于实时显示子进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆