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

Python3.8运行psutil自重启代码报Process无get_open_files属性如何解决

psutil自重启脚本报错修复方案

错误原因

报错'Process' object has no attribute 'get_open_files'是高版本psutil库的接口变更导致的,早期版本的get_open_files()方法在后续版本中被重命名为open_files(),二者功能完全一致。

直接修复方案

将代码中调用get_open_files()的部分替换为open_files()即可,修改后的完整代码如下:

import os
import sys
import psutil
import logging

def restart_program():
    """Restarts the current program, with file objects and descriptors
       cleanup
    """

    try:
        p = psutil.Process(os.getpid())
        # 仅修改此处方法名,其余逻辑保持不变
        for handler in p.open_files() + p.connections():
            os.close(handler.fd)
    except Exception as e:
        logging.error(e)

    python = sys.executable
    os.execl(python, python, *sys.argv)

兼容新旧版本的可选方案

如果运行环境可能同时存在高低版本psutil,可以增加方法存在性判断,兼容两种调用逻辑:

try:
    p = psutil.Process(os.getpid())
    # 优先匹配高版本方法,不存在则回退到旧版本方法
    get_open_files = p.open_files if hasattr(p, 'open_files') else p.get_open_files
    for handler in get_open_files() + p.connections():
        os.close(handler.fd)
except Exception as e:
    logging.error(e)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:06:04