我有python方法,该方法执行传递给它的命令。现在您可以看到,命令完成后,它会打印出命令的输出。是否可以在执行时实时打印出命令的输出,然后将命令输出捕获到字符串中以进行后续处理?
import subprocess
from subprocess import check_output
def execute_cmd(args):
try:
out = check_output(args, stderr=subprocess.STDOUT, universal_newlines=True).split('\n')
clean_non_empty_lines = []
for line in out:
print(line)
line = line.strip()
if line:
clean_non_empty_lines += [line]
return clean_non_empty_lines
except subprocess.CalledProcessError as e:
raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))