我正在尝试导入脚本,如下所示:
Runtime.PythonDLL = "python311.dll";
PythonEngine.Initialize();
using (Py.GIL())
{
var script = Py.Import("example");
var result = script.InvokeMethod("foo");
}
脚本如下:
def foo():
return 1
它位于 python 的 site-packages 文件夹中名为 example 的文件夹中。示例文件夹还有一个空的 init.py 文件。
当我运行上面的 C# 代码时,出现以下错误: Python.Runtime.PythonException:'模块'example'没有属性'foo''
任何帮助将不胜感激。
using Python.Runtime;
// Initialize the Python engine
PythonEngine.Initialize();
// Load the Python script
dynamic script = PythonEngine.ModuleFromString("example", File.ReadAllText("example.py"));
// We call the Python function
dynamic output = script.foo();
// Print the resule in the console.
Console.WriteLine(output);
(未经测试)
https://www.educative.io/answers/how-to-call-a-python-function-from-c-sharp
您需要添加 py 文件的路径,例如:
dynamic sys = Py.Import("sys");
sys.path.append("../path_to_py_files/");
之后您可以尝试您的代码:
dynamic script = Py.Import("example");
dynamic result = script.InvokeMethod("foo");