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")

 

posted @ 2019-07-30 17:26  1553  阅读(3416)  评论(0编辑  收藏  举报