python subprocess popen sterr_python-将subprocess.Popen输出到文件

这篇博客探讨了如何使用Python的subprocess模块运行多个子进程,并将它们的输出合并到同一个日志文件中。作者遇到的问题是,当输出量过大时,会导致进程挂起。为了解决这个问题,他们设置了超时并使用了Alarm异常来中断长时间运行的子进程。此外,还实现了信号处理函数来优雅地关闭子进程并确保日志正确写入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我同时运行两个子流程,并将两者的输出保存到单个日志文件中。 我还建立了一个超时来处理挂起的子进程。 当输出太大时,总是触发超时,并且任何一个子进程的stdout都不会保存到日志文件中。 上面Alex提出的答案并不能解决。

# Currently open log file.

log = None

# If we send stdout to subprocess.PIPE, the tests with lots of output fill up the pipe and

# make the script hang. So, write the subprocess's stdout directly to the log file.

def run(cmd, logfile):

#print os.getcwd()

#print ("Running test: %s" % cmd)

global log

p = subprocess.Popen(cmd, shell=True, universal_newlines = True, stderr=subprocess.STDOUT, stdout=logfile)

log = logfile

return p

# To make a subprocess capable of timing out

class Alarm(Exception):

pass

def alarm_handler(signum, frame):

log.flush()

raise Alarm

####

## This function runs a given command with the given fl

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值