如何抓取多进程中的报错

文章介绍了在多进程编程中,错误信息无法正常打印到终端的问题,提出了一种解决方案。通过定义`LogExceptions`类,捕获并使用`multiprocessing.get_logger().error`打印异常,同时保留原始异常以便进一步处理。在调用多进程函数时,如`data_write`,可以使用`pool.apply_async`结合`LogExceptions`来包装函数调用,确保错误能被记录和显示。
摘要由CSDN通过智能技术生成

多进程中的很多报错并不会打印到终端,这给我们调试代码带来很大麻烦。

现在用这个方法就可以把报错打印出来,也是我实习过程中偷师出来,给自己也记录一下。

def error(msg, *args):
    return multiprocessing.get_logger().error(msg, *args)


class LogExceptions(object):
    def __init__(self, callable):
        self.__callable = callable
        return

    def __call__(self, *args, **kwargs):
        try:
            result = self.__callable(*args, **kwargs)

        except Exception as e:
            # Here we add some debugging help. If multiprocessing's
            # debugging is on, it will arrange to log the traceback
            error(traceback.format_exc())
            # Re-raise the original exception so the Pool worker can
            # clean up
            raise

        # It was fine, give a normal answer
        return result

    pass

随后在自己调用多进程执行函数时,把这个LogExceptions函数套在我们需要执行的函数上,如下,套在data_write上:

for i in range(cnt):
        multi_rows = rows[i*step:(i+1)*step]
        # data_write(multi_rows,model,preprocess,device)
        pool.apply_async(LogExceptions(data_write),(multi_rows,model,preprocess,device,))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小馆长布鲁克

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值