天天看點

Python擷取指令實時輸出-原樣彩色輸出并傳回輸出結果

經試驗顯示效果不錯。

#!/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")