python獲取實時命令行輸出


我們平時用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)

在調用的命令沒有結束之前,依然可以輸出其結果.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM