我试图使用依赖于.NET6的System.Text.Json
库,该库无法使用pythonnet导入:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ModuleNotFoundError: No module named 'System'
在python中,检查pythonnet
默认添加的程序集,可以看到它没有随加载的System.Text.Json
命名空间一起发布:
import clr
print("[", ", ".join(clr.ListAssemblies(False)), "]")
产出:
[ mscorlib, clrmodule, Python.Runtime, System.Core, System.Configuration, System.Xml, System, __CodeGenerator_Assembly, e__NativeCall_Assembly ]
然后我尝试添加System.Text.Json
,它似乎成功了:
import clr
import sys
DOTNET_PATH: str = {YOUR PATH TO .NET6 DLLs}
sys.path.append(DOTNET_PATH)
clr.AddReference("System.Text.Json")
print("[", ", ".join(clr.ListAssemblies(False)), "]")
产出:
[ ..., System, System.Text.Json, System.Runtime, ... ]
但是,尝试从命名空间导入类:
from System.Text.Json import JsonDocument
继续提出:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ModuleNotFoundError: No module named 'System'
(我还尝试添加了随.dll 6.0.1附带的每一个.NET,但都没有成功)
为了成功地从这个命名空间导入,我还需要使用其他机制吗?(及相关)
发布于 2022-01-27 19:22:59
要使用.NET核心/.NET 5+程序集,您需要pythonnet3.0.0或更高版本(目前正在预览中)。
还需要显式加载coreclr:
from clr_loader import get_coreclr
from pythonnet import set_runtime
coreclr = get_coreclr("/full/path/to/app.runtimeconfig.json")
set_runtime(coreclr)
// here goes the rest of your code
runtimeconfig.json
文件是由dotnet publish
创建的
https://stackoverflow.com/questions/70882963
复制相似问题