python执行shell实时输出

1.使用readline可以实现

import subprocess


def run_shell(shell):
    cmd = subprocess.Popen(shell, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
                           stdout=subprocess.PIPE, universal_newlines=True, shell=True, bufsize=1)
    # 实时输出
    while True:
        line = cmd.stdout.readline()
        print(line, end='')
        if subprocess.Popen.poll(cmd) == 0:  # 判断子进程是否结束
            break

    return cmd.returncode


if __name__ == '__main__':
    print(run_shell("ping www.baidu.com"))

2.readline可能导致卡死,官方推荐使用communicate,但是如果还是使用subprocess.PIPE,执行完命令后才能拿到标准输出,替换成sys.stdout就能达到实时输出效果,代码附上

import subprocess
import sys


def run_shell(shell):
    cmd = subprocess.Popen(shell, stdin=subprocess.PIPE, stderr=sys.stderr, close_fds=True,
                           stdout=sys.stdout, universal_newlines=True, shell=True, bufsize=1)

    cmd.communicate()
    return cmd.returncode


if __name__ == '__main__':
    print(run_shell("ping www.baidu.com"))

posted @   雪山飞猪  阅读(11070)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2018-09-17 python干掉pycache
2018-09-17 python使用虚拟环境
2015-09-17 php动态获取函数参数
2015-09-17 设计模式之: 代理模式
点击右上角即可分享
微信分享提示