You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux环境下Pillow库Image类__del__方法抛出无效异常的解决办法

解决措施

针对Linux环境下Pillow的Image类偶尔触发的__del__方法异常,除提交bug外,可尝试以下几种解决办法:

  • 显式管理Image对象生命周期
    避免依赖Python自动垃圾回收触发__del__,手动释放资源:

    • 手动调用close()并置空对象:
      img = Image.open("your_image.jpg")
      # 执行图片处理逻辑
      img.close()
      img = None
      
    • 使用上下文管理器自动释放:
      with Image.open("your_image.jpg") as img:
          # 执行图片处理逻辑
          pass
      
  • 重写Image类的__del__方法
    自定义子类修复异常捕获逻辑,确保只捕获BaseException子类:

    from PIL import Image as PILImage
    
    class FixedImage(PILImage):
        def __del__(self):
            try:
                super().__del__()
            except BaseException:
                # 可按需添加日志记录或直接忽略
                pass
    

    后续使用FixedImage替代原Image类进行图片操作。

  • 升级Pillow到最新稳定版
    该异常可能已在后续版本中被修复,执行命令升级:

    pip install --upgrade pillow
    
  • 禁用Pillow的tkinter插件(非必需时)
    若代码不需要tkinter相关功能,通过环境变量禁用:

    export PIL_DISABLE_TKINTER=1
    python your_script.py
    

    避免加载tkinter相关代码,绕过异常触发路径。

内容的提问来源于stack exchange,提问作者Joymaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 22:32:06