chenqionghe

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"))

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
  • 2021-11-12
  • 2021-11-28
  • 2021-08-15
猜你喜欢
  • 2022-12-23
  • 2022-01-24
  • 2022-12-23
  • 2021-11-17
  • 2021-12-23
  • 2022-12-23
  • 2022-01-22
相关资源
相似解决方案