对于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