使用Hatchling构建PIP项目时,如何解决UserDict.py的FileNotFoundError?
问题描述
我在为SkillMetrics包的新版本构建pip包时遇到了问题,遵循《Packaging Python Projects》指南使用Hatchling构建系统(而非setuptools),执行python3 -m build时出现如下错误:
% python3 -m build * Creating venv isolated environment... * Installing packages in isolated environment... (hatchling) * Getting dependencies for sdist... * Building sdist... * Building wheel from sdist * Creating venv isolated environment... * Installing packages in isolated environment... (hatchling) * Getting dependencies for wheel... * Building wheel... Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pep517/in_process/_in_process.py", line 351, in <module> main() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pep517/in_process/_in_process.py", line 333, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pep517/in_process/_in_process.py", line 249, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, File "/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-env-tzuwjpjg/lib/python3.10/site-packages/hatchling/build.py", line 41, in build_wheel return os.path.basename(next(builder.build(wheel_directory, ['standard']))) File "/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-env-tzuwjpjg/lib/python3.10/site-packages/hatchling/builders/plugin/interface.py", line 144, in build artifact = version_api[version](directory, **build_data) File "/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-env-tzuwjpjg/lib/python3.10/site-packages/hatchling/builders/wheel.py", line 318, in build_standard record = archive.add_file(included_file) File "/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-env-tzuwjpjg/lib/python3.10/site-packages/hatchling/builders/wheel.py", line 59, in add_file file_stat = os.stat(included_file.path) FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/jy/p3021mrj5d54jd3wf686d0rc0000gp/T/build-via-sdist-z4709rdv/skillmetrics-1.1.9/mitmenv/lib/python2.7/UserDict.py' ERROR Backend subprocess exited when trying to invoke build_wheel
解决方法
错误核心是构建系统尝试打包项目中的虚拟环境目录mitmenv,而其中的Python2.7文件在构建环境中不存在。按以下步骤修复:
配置Hatchling排除不必要目录
在项目根目录的pyproject.toml中添加打包规则,明确排除虚拟环境、缓存文件等:[tool.hatch.build] exclude = [ "mitmenv/**/*", "__pycache__/**/*", "*.pyc", "build/*", "dist/*" ]完善.gitignore文件
确保.gitignore包含以下内容,避免不必要文件被纳入版本控制和打包:mitmenv/ __pycache__/ *.pyc build/ dist/ *.egg-info/清理构建缓存
删除旧构建产物和临时文件后重新执行构建:rm -rf dist/ build/ *.egg-info/ python3 -m build --clean检查硬编码路径
排查代码或配置文件中是否存在硬编码的Python2.7路径引用,确保所有路径适配Python3环境。
内容的提问来源于stack exchange,提问作者Peter Rochford
相关产品推荐
相关产品推荐

