subprocess.Popen stdout重定向內容實時獲取


python 打開一個新進程執行系統命令, test 執行完才能獲取返回, test1 實時獲取返回結果

import subprocess

def test(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    lines = p.stdout.readlines()
    for line in lines:
        tmp = line.decode('gbk').strip()
        print(tmp)

def test1(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    for i in iter(p.stdout.readline, ''):
        if len(i) < 1:
            break
        print(i.decode('gbk').strip())

if __name__ == '__main__':
    test("ping www.baidu.com")
    test1("ping www.baidu.com")

 


免責聲明!

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



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