zoukankan      html  css  js  c++  java
  • python-subprocess 返回数据实时更新

    对于shell的命令实时更新

    import subprocess

    cmd = "你的shell命令"

    res = subprocess.Popen(shell, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    for line in iter(res.stdout.readline,'b'):

        line = line.rstrip().decode('utf8')

        # 你的操作

        if(subprocess.Popen.poll(res) is not None):

            if(line==""):

                break

        res.stdout.close()

    注: 上述写法完美解决实时输出问题。

    下面在提供几种写法,有待进一步测试:

    =============第一种

    subprocess的返回结果从缓冲区中读取,需要刷新缓冲区,故而设置较小buffsize

    res = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)

    for line in iter(res.stdout.readline, b''):

        print (line)

    res.stdout.close()

    res.wait()

    =============第二种 

    使用while,使用感受一般

    res = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)

    while True:

        line = res.stdout.readline()

        line = line.rstrip().decode('utf8‘)

        print(line)

        if(line =='' and res.poll() !=None):

            break

  • 相关阅读:
    Java内部类详解
    浅谈Java中的深拷贝和浅拷贝(转载)
    native为本地方法
    Java NIO:NIO概述
    Java NIO:浅析I/O模型
    Hash表
    浅谈Java中的hashcode方法
    spring boot学习(转)
    Spring Boot修改内置Tomcat端口号
    K8S
  • 原文地址:https://www.cnblogs.com/wind-man/p/13679140.html
Copyright © 2011-2022 走看看