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