Python获取命令实时输出-原样彩色输出并返回输出结果的示例

(编辑:jimmy 日期: 2024/9/27 浏览:2)

经试验显示效果不错。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import subprocess


# 与在命令窗口执行显示效果相同,如有彩色输出可保留,但不能返回结果
def run(command):
  subprocess.call(command, shell=True)


# 实时输出但不可显示彩色,可以返回结果
def sh(command, print_msg=True):
  p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  lines = []
  for line in iter(p.stdout.readline, b''):
    line = line.rstrip().decode('utf8')
    if print_msg:
      print(">", line)
    lines.append(line)
  return lines


print('run():')
run("ping www.baidu.com")
print('\n\nsh():')
run("ping www.baidu.com")

以上这篇Python获取命令实时输出-原样彩色输出并返回输出结果的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。