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")
上一篇:VB中的API详解


下一篇:Python实时语音识别控制