在BitBucket上使用pythonnet加载特定.NET程序包失败问题
Pythonnet调用.NET DLL在BitBucket CI中出现System.IO.FileLoadException(版本7.0.0.0)的解决思路
问题场景
本地环境(Python 3.11 + pythonnet 3.0.1 + .NET 6.0.21)中,调用依赖System.Text.Json 7.0.3的自定义.NET DLL完全正常,但在BitBucket CI流程中执行单元测试时触发System.IO.FileLoadException,提示无法加载版本7.0.0.0的System.Text.Json程序集。CI流程已完成以下操作:
- 用
mcr.microsoft.com/dotnet/sdk:6.0镜像构建虚拟.NET 6 exe,触发NuGet包下载并生成产物 - 在
python:3.11镜像中搭建pythonnet环境,成功安装pythonnet 3.0.1,sys.path配置符合预期 - 归档文件夹中存在
System.Text.Json.dll,且能加载自定义DLL和System命名空间类
排查与解决步骤
1. 添加程序集绑定重定向配置
在自定义DLL的同目录创建runtimeconfig.json,明确指定System.Text.Json的版本绑定规则,避免CI环境中版本匹配冲突:
{ "runtimeOptions": { "assemblyBinding": { "dependencies": { "System.Text.Json": { "version": "7.0.3", "publicKeyToken": "cc7b13ffcd2ddd51" } } } } }
也可在Python代码初始化pythonnet时手动传入配置:
import clr from clr_loader import get_coreclr from pythonnet import set_runtime runtime_config = { "runtimeOptions": { "assemblyBinding": { "dependencies": { "System.Text.Json": {"version": "7.0.3", "publicKeyToken": "cc7b13ffcd2ddd51"} } } } } set_runtime(get_coreclr(runtime_config)) clr.AddReference("System.Text.Json")
2. 强制指定DLL加载路径
确保CI环境中优先加载归档文件夹内的System.Text.Json.dll,避免全局.NET环境中的旧版本干扰:
- 直接通过完整路径加载DLL:
import os import clr json_dll_path = os.path.join("path/to/your/archive", "System.Text.Json.dll") clr.AddReference(json_dll_path) - 设置环境变量指定优先搜索目录:
export CORE_LIBRARY_PATH=/path/to/your/archive:$CORE_LIBRARY_PATH
3. 验证NuGet包完整性
在CI的.NET构建步骤中,添加包下载验证逻辑,确保System.Text.Json包完整:
dotnet restore --verbosity detailed # 检查目标版本的DLL是否存在 ls -la ./packages/System.Text.Json/7.0.3/lib/net6.0/
同时确认归档产物时,将NuGet包lib/net6.0目录下的所有文件完整复制到指定路径,避免依赖遗漏。
4. 配置coreclr初始化参数
初始化coreclr时指定appdomain_base为自定义DLL所在目录,确保程序集搜索路径正确:
import clr from clr_loader import get_coreclr from pythonnet import set_runtime runtime = get_coreclr( runtime_config="path/to/your/runtimeconfig.json", appdomain_base="/path/to/your/dll/directory" ) set_runtime(runtime)
内容的提问来源于stack exchange,提问作者Denise Skidmore
相关产品推荐
相关产品推荐

