python-subprocess 返回數據實時更新


對於shell的命令實時更新

import subprocess

cmd = "你的shell命令"

res = subprocess.Popen(shell, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in iter(res.stdout.readline,'b'):

    line = line.rstrip().decode('utf8')

    # 你的操作

    if(subprocess.Popen.poll(res) is not None):

        if(line==""):

            break

    res.stdout.close()

 

注: 上述寫法完美解決實時輸出問題。

下面在提供幾種寫法,有待進一步測試:

=============第一種

subprocess的返回結果從緩沖區中讀取,需要刷新緩沖區,故而設置較小buffsize

res = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)

for line in iter(res.stdout.readline, b''):

    print (line)

res.stdout.close()

res.wait()

=============第二種 

使用while,使用感受一般

res = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)

while True:

    line = res.stdout.readline()

    line = line.rstrip().decode('utf8‘)

    print(line)

    if(line =='' and res.poll() !=None):

        break

 


免責聲明!

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



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