1、问题:由于打印较多,buff满了之后会导致进程卡死
例:
import subprocess
cmd = '运行程序的命令行'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
p.wait(60)
if p.poll() is None or p.poll() != 0:
print(f'Failed to run {cmd}. Error code is {p.poll()}')
else:
output = str(p.stdout.read() #
此时会由于执行命令行程序时输出的信息较多,导致进程卡死,直到超时结束;
2、解决方法:创建一个临时文件,把输出结果存到临时文件中,从临时文件中读取结果
例:
import os
import subprocess
import tempfile
cmd = '需要执行的命令行'
try:
# 得到一个临时文件对象, 调用close后,此文件从磁盘删除
out_temp = tempfile.TemporaryFile(mode='w+')
# 获取临时文件的文件号
fileno = out_temp.fileno()
# stdout=fileone,把输出结果存到临时文件中
p = subprocess.Popen(cmd, shell=True, stdout=fileno)
time.sleep(2)
p.wait(60)
if p.poll() is None or p.poll() != 0:
print(f'Failed to run {cmd}. Error code is {p.poll()}')
else:
# 从临时文件中读取执行shell的返回结果
out_temp.seek(0) # 表示从文件开头开始读取;用于在文件中移动文件指针的位置
output = out_temp.read().split('\n')
print(output)
except Exception as e:
print(e)
finally:
if out_temp:
out_temp.close()