做工程時使用subprocess模塊時,遇到子進程的運行信息無法輸出的情況。
如test.py:
import time
for i in range(5):
print i
time.sleep(1)
使用subprocess模塊如下:
import subprocess
cmd = 'python /home/cabin/Desktop/test.py'
p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,executable="/bin/bash")
while p.poll() is None:
line = p.stdout.readline()
line = line.strip()
if line:
print('stdout info: [{}]'.format(line))
if line:
time.sleep(10)
print('process:success')
break
try:
p.kill()
except OSError:
pass
理論上在line接收到test.py的運行信息後,加10s延時打印程序運行成功,p模塊。實際運行中會發現p並沒有接收到任何test.py的運行信息,line值實際上是爲None,循環一直無法退出,而單獨運行test.py在終端是能正常打印信息的。
解決方案參考:https://blog.csdn.net/cnweike/article/details/73620250。
實際上subprocess模塊中stdout所接收的運行信息不是print打印出來的信息,而應該是標準的輸出信息,同理,stderr接收的是標準的錯誤信息。在python中應爲sys.stdout.write以及sys.stderr.write。故test.py應改爲如下形式:
import time
for i in range(5):
sys.stdout.write(i)
sys.stdout.flush()
time.sleep(1)
其中sys.stdout.flush()爲手動清空標準輸出的存,使得test.py的信息能實時被subprocess模塊接收。