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

如何用cx_freeze冻结Python测试代码?运行报错求助

解决cx_Freeze打包pytest脚本时的importlib_metadata.PackageNotFoundError

我之前打包带pytest的Python脚本时也碰到过一模一样的问题,本质是cx_Freeze没有自动把importlib_metadata这个依赖包包含到最终的可执行文件里,而pytest在运行时需要它来读取版本信息。

问题重现的错误信息

... __version__ = version(__name__)
File "C:\Python36-32\lib\site-packages\importlib_metadata\__init__.py", line 457, in version
return distribution(package).version
File "C:\Python36-32\lib\site-packages\importlib_metadata\__init__.py", line 430, in distribution
return Distribution.from_name(package)
File "C:\Python36-32\lib\site-packages\importlib_metadata\__init__.py", line 184, in from_name
raise PackageNotFoundError(name)
importlib_metadata.PackageNotFoundError: importlib_metadata

你的原始setup.py

from cx_Freeze import setup, Executable
import pytest
build_exe_options = {"includes": pytest.freeze_includes() }
setup(
name = "runtests",
version = "0.1",
description = "runtests",
executables = [Executable("runtest.py")],
options = {"build_exe": build_exe_options},
)

两种可行的解决方案

方案1:手动将importlib_metadata添加到includes列表

pytest.freeze_includes()返回的依赖列表里并没有包含importlib_metadata,所以我们需要手动把它加进去:

from cx_Freeze import setup, Executable
import pytest

# 把importlib_metadata追加到includes列表里
build_exe_options = {"includes": pytest.freeze_includes() + ["importlib_metadata"]}

setup(
    name="runtests",
    version="0.1",
    description="runtests",
    executables=[Executable("runtest.py")],
    options={"build_exe": build_exe_options},
)

方案2:使用packages参数显式指定要包含的包

如果上面的方法还是不行,可以尝试用packages参数来指定需要打包的整个包:

from cx_Freeze import setup, Executable
import pytest

build_exe_options = {
    "includes": pytest.freeze_includes(),
    "packages": ["importlib_metadata"]
}

setup(
    name="runtests",
    version="0.1",
    description="runtests",
    executables=[Executable("runtest.py")],
    options={"build_exe": build_exe_options},
)

补充说明

你用的是Python 3.6,这个版本里importlib_metadata还不是标准库的一部分(Python 3.8+才内置),所以它是作为第三方包安装的,cx_Freeze默认不会自动识别这种间接依赖,必须手动指定包含。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:34:10