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

关闭Selenium Chrome进程引发“Too many open files”错误的彻底解决方法

解决Selenium Chrome进程残留导致的"Too many open files"错误

问题背景

持续运行的代码通过Selenium维护Chrome进程,因加载扩展、清理数据或连接丢失需重启进程,但重启后残留大量打开文件,长期运行触发"Too many open files"错误。尝试自定义kill_driver函数及lsof | grep chrome | awk '{print $2}' | xargs -r kill命令,仅能部分缓解,仍存在文件句柄堆积。

彻底解决方案

1. 递归终止Chrome全进程树

Chrome采用多进程架构,仅杀死主进程会遗留渲染、GPU等子进程,导致文件句柄泄漏。修改kill_driver函数,遍历并杀死所有关联进程:

import os
import psutil
import shutil

def kill_driver(driver, temp_dir=None):
    # 优先尝试正常退出
    try:
        driver.quit()
        print("Driver正常退出")
    except Exception as e:
        print(f"正常退出失败: {str(e)}")
        # 获取Chrome主进程并递归杀死所有子进程
        try:
            main_pid = driver.service.process.pid
            if psutil.pid_exists(main_pid):
                main_proc = psutil.Process(main_pid)
                # 获取所有子进程(递归包含所有层级)
                all_procs = [main_proc] + main_proc.children(recursive=True)
                # 逐个杀死进程
                for proc in all_procs:
                    try:
                        proc.kill()
                        print(f"已终止进程 {proc.pid}")
                    except Exception as proc_e:
                        print(f"终止进程 {proc.pid} 失败: {str(proc_e)}")
        except Exception as e:
            print(f"处理进程失败: {str(e)}")
    
    # 清理临时用户目录(如果使用了临时目录)
    if temp_dir:
        try:
            shutil.rmtree(temp_dir)
            print(f"已删除临时目录 {temp_dir}")
        except Exception as e:
            print(f"删除临时目录失败: {str(e)}")
    
    # 清理当前Python进程的僵尸子进程
    try:
        while True:
            pid, _ = os.waitpid(-1, os.WNOHANG)
            if pid == 0:
                break
            print(f"已清理僵尸进程 {pid}")
    except OSError as e:
        if e.errno != os.errno.ECHILD:
            print(f"清理僵尸进程出错: {str(e)}")

2. 使用临时用户数据目录避免文件残留

Chrome的用户数据目录会留存大量缓存、日志文件,即使进程退出也可能残留未关闭的句柄。每次启动Chrome时创建临时目录,退出后彻底删除:

import tempfile
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

def create_chrome_driver():
    options = Options()
    # 创建临时用户数据目录
    temp_dir = tempfile.mkdtemp(prefix="chrome_")
    options.add_argument(f"--user-data-dir={temp_dir}")
    # 禁用共享内存泄漏风险
    options.add_argument("--disable-dev-shm-usage")
    # 禁用不必要的组件减少进程数
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    
    driver = webdriver.Chrome(options=options)
    return driver, temp_dir

# 使用示例
driver, temp_dir = create_chrome_driver()
# 执行业务操作...
# 退出时调用kill_driver
kill_driver(driver, temp_dir)

3. 定位非Chrome相关的文件句柄泄漏

如果仍存在句柄堆积,需检查Python进程自身的文件泄漏:

  • 查看当前Python进程的所有打开文件:lsof -p $(pgrep -f 你的脚本名.py)
  • 重点排查代码中是否有未关闭的文件、日志流、数据库连接等资源,确保所有资源在使用后显式关闭。

4. 调整系统文件句柄限制

若业务确实需要大量文件句柄,可临时或永久调整系统限制:

  • 临时生效(当前会话):ulimit -n 65535
  • 永久生效:编辑/etc/security/limits.conf,添加以下内容后重启系统:
* soft nofile 65535
* hard nofile 65535

5. 用上下文管理器确保Driver自动回收

使用with语句管理Driver,确保即使发生异常也能自动调用quit():

driver, temp_dir = create_chrome_driver()
try:
    with driver:
        # 执行业务操作
        driver.get("https://example.com")
finally:
    kill_driver(driver, temp_dir)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 15:18:26