Python 3.12中替换imp.load_source的兼容方案(适配Chromium构建)
替换
imp.load_source的兼容方案(Python 3.6+) 问题背景
Python 3.12已完全移除imp模块,导致依赖imp.load_source的脚本运行失败。我们可以使用Python标准库中的importlib模块替代,该模块从Python 3.3开始引入,3.6+版本中API稳定,完全满足多版本兼容需求。
具体修改方案
步骤1:调整导入语句
移除对imp模块的导入,添加importlib.util的导入(若脚本未导入sys则同时导入):
import sys import importlib.util
步骤2:修改load_module函数的加载逻辑
将原函数中return imp.load_source(fullname, filepath)的代码段替换为以下兼容逻辑:
def load_module(self, fullname): """Loads the module specified by |fullname| and returns the module.""" if fullname in sys.modules: # Per PEP #302, if |fullname| is in sys.modules, it must be returned. return sys.modules[fullname] if (not fullname.startswith('google.protobuf.') or not self._module_exists(fullname)): # Per PEP #302, raise ImportError if the requested module/package # cannot be loaded. This should never get reached for this simple loader, # but is included for completeness. raise ImportError(fullname) filepath = self._fullname_to_filepath(fullname) # 替换imp.load_source的兼容代码 spec = importlib.util.spec_from_file_location(fullname, filepath) if spec is None: raise ImportError(f"Cannot find module spec for {fullname} at {filepath}") module = importlib.util.module_from_spec(spec) # 遵循PEP302规范,先将模块加入sys.modules再执行加载 sys.modules[fullname] = module spec.loader.exec_module(module) return module
方案说明
- 完全基于Python标准库实现,无需额外安装依赖,符合Linux发行版自带库的要求。
- 兼容Python 3.6至3.12的所有版本,满足Chromium对旧版Python的支持需求,补丁更容易被上游接受。
- 严格遵循PEP302规范,与原
imp.load_source的行为保持一致,不会引入额外逻辑变更。
内容的提问来源于stack exchange,提问作者kinokijuf
相关产品推荐
相关产品推荐

