我們平時用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)
在調用的命令沒有結束之前,依然可以輸出其結果.