Pythonnet:如何使用嵌入式Python解释器?
我正在尝试通过 C# 使用嵌入的 Python 解释器,使用的是 pythonnet(可以在 https://github.com/renshawbay/pythonnet 找到与 Python3 兼容的版本)。
我的解释器位于 D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime,并且包含了 Python 分发版中的 "Lib" 和 "Libs" 文件夹。
我测试了以下代码:
<!-- language: c# -->
PythonEngine.PythonHome = @"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
PythonEngine.ProgramName = "PythonRuntime";
PythonEngine.Initialize();
using (Py.GIL())
{
PythonEngine.RunSimpleString("print(1)");
}
但是,它没有成功。我遇到了一个错误:“SystemError: PyEvalCodeEx: NULL globals”。每次我尝试从 Python 获取一个对象时,代码都会失败。
我哪里做错了呢?
1 个回答
1
我想我找到了答案。如果我添加一个对pythonnet提供的“clr”模块的引用,它就能正常工作了。
PythonEngine.PythonHome = @"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
PythonEngine.ProgramName = "PythonRuntime";
PythonEngine.Initialize();
// ==>
PyObject a = PythonEngine.ImportModule("clr");
using (Py.GIL())
{
PythonEngine.RunSimpleString("print(1)");
}