无法在asp.net core web API项目中运行Python

问题描述 投票:0回答:1

我正在使用 Core 6 和 Pythonnet 包。

我创建了一个Python文件名example.py

def add(a, b):
return a + b

我创建一个类名

PythonScriptRunner
:

public PythonScriptRunner()
{
    Runtime.PythonDLL = @"C:\Python312\python312.dll"; // I installed the python it this path
    PythonEngine.Initialize();
}

并将其添加到program.cs中

builder.Services.AddScoped<PythonScriptRunner>();

然后我创建一个控制器

public IActionResult Test(int a, int b)
{
     using (Py.GIL())
     {
         dynamic python = Py.Import("example"); // The error at this line.
         int result = python.add(a, b).As<int>();
         return Ok(result);
     }
}

例外是:

Python.Runtime.PythonException:“没有名为“example”的模块。

python asp.net-core asp.net-web-api nuget
1个回答
0
投票

无法在asp.net core web API项目中运行Python。例外是: Python.Runtime.PythonException:“没有名为“example”的模块。

根据您的代码片段和共享错误,表明Python解释器在尝试导入名为“example”的模块时无法找到它。

在您的场景中,您尝试在 ASP.NET Core 应用程序中导入名为“example”的模块,但 Python 解释器无法找到它。

为了解决此问题,您应该调查以下几件事:

首先,请验证您的执行路径是否正确。您可能在导入语句中输入错误,或者

example.py
文件的路径可能错误。

例如,如果 example.py 位于项目根目录中,那么您应该尝试如下所示:

 dynamic python = Py.Import("example");

但是如果您的文件位于子文件夹中,请尝试这样:

dynamic python = Py.Import("subdirectory.example");

另一个重要的事情是,如果

example.py
不在 Python 的默认搜索路径中,您可能需要使用
PythonEngine.PythonPath.Add()

显式添加其目录路径

此外,请确保

PythonEngine.Initialize()
仅被调用一次,通常在像单例类这样的集中位置。

最后,不要只指定模块名称,而是尝试使用“example.py”文件的绝对路径。

注意:参考此官方文档进行配置

© www.soinside.com 2019 - 2024. All rights reserved.