DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Python 报错 OSError: [Errno 24] Too many open files 文件句柄泄露

分析 Python 高并发网络请求或文件处理未关闭句柄报 Errno 24 根因,提供 with 上下文管理器规范与 ulimit 调优步骤。

问题现象

Python 服务在高并发运行一段时间后,处理任何新文件或网络连接时崩溃退出:

Traceback (most recent call last):
  File "crawler.py", line 45, in fetch
    with open(f"/tmp/{i}.txt", "w") as f:
OSError: [Errno 24] Too many open files: '/tmp/1024.txt'
-- 或者提示:
socket.error: [Errno 24] Too many open files

触发根因

  1. 未关闭文件或套接字(缺少上下文管理器):在循环中直接调用 f = open(...) 而未调用 f.close(),依赖不可预期的垃圾回收机制。
  2. 操作系统针对该 Python 进程设置的 ulimit -n 过小(默认通常为 1024)。

诊断排查步骤

  1. 检查 Python 进程当前已打开的文件句柄总数:
ls -l /proc/<pid>/fd | wc -l
  1. 查看限制:
cat /proc/<pid>/limits | grep "open files"

解决步骤与操作命令

步骤一:严格使用 with 上下文管理器(杜绝代码句柄泄露)

确保每个打开的操作均在退出作用域后自动释放底层系统描述符:

# 正确规范:
with open(filepath, 'w') as f:
    f.write(data)
# 作用域结束自动执行 f.close()

步骤二:临时调大当前终端的 ulimit 配额

在运行 Python 脚本前执行:

ulimit -n 65535
python main.py

步骤三:持久化修改用户的句柄限制

编辑 /etc/security/limits.conf:

* soft nofile 65535
* hard nofile 65535

重新登录终端运行,并发处理海量文件平稳顺畅。