我们平时用os.system和subprocess执行命令并获取返回值, 但获取返回值都是在命令完全执行完毕后,如果命令持续输出不会结束,该如何获取实时输出呢?

exer16.py

import time
def fun():
    for i in range(6):
        print("{:*^20}".format(i))
        time.sleep(1)

fun()

exer15.py

import subprocess
cmd="python exer16.py"
ret = subprocess.Popen(cmd,shell=True,
                 stdin=subprocess.PIPE,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE,
                 cwd=r"C:\Users\23798\Desktop\desktop\my_note\my_project")
l=[]
for i in iter(ret.stdout.readline,b""):
    print(i.decode().strip())
    l.append(i.decode().strip())
print("finally------>",l)

在调用的命令没有结束之前,依然可以输出其结果.

python 执行source python 执行命令并获取输出_python 执行source