Python get command real time output sample color output as is and return output result
- 2021-07-13 05:46:07
- OfStack
Experiments show that the effect is good.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import subprocess
# The display effect is the same as that performed in the command window. If there is color output, it can be preserved, but the result cannot be returned
def run(command):
subprocess.call(command, shell=True)
# Output in real time but not in color, and can return results
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")