You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 Web API用Pythonnet调用Python模块报错:找不到example

解决Pythonnet在ASP.NET Core 6中找不到自定义模块的问题

出现Python.Runtime.PythonException: 找不到名为‘example’的模块的原因是Python引擎的默认搜索路径不包含你存放example.py的目录,需要手动将该目录添加到Python的sys.path中。

以下是具体解决方法:

方法一:在Python引擎初始化时添加路径

修改PythonScriptRunner类的构造函数,初始化Python引擎后立即添加脚本所在目录到sys.path:

using System.Reflection;
using System.IO;
using Python.Runtime;

public PythonScriptRunner()
{
    Runtime.PythonDLL = @"C:\Python312\python312.dll";
    PythonEngine.Initialize();

    // 获取当前程序集所在目录(example.py需放在此目录或子目录)
    var scriptDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    // 如果example.py在项目根目录的Scripts子文件夹,可改为:
    // var scriptDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "../Scripts");
    // 注意路径需根据实际存放位置调整

    dynamic sys = Py.Import("sys");
    sys.path.append(scriptDir);
}

方法二:在导入模块前临时添加路径

如果不想修改初始化逻辑,也可以在控制器的Test接口中导入模块前添加路径:

using System.IO;
using Python.Runtime;

public IActionResult Test(int a, int b)
{
     using (Py.GIL())
     {
         // 添加example.py所在目录到Python搜索路径
         dynamic sys = Py.Import("sys");
         // 假设example.py存放在项目根目录的Scripts文件夹下
         var scriptPath = Path.Combine(Directory.GetCurrentDirectory(), "Scripts");
         sys.path.append(scriptPath);

         dynamic python = Py.Import("example");
         int result = python.add(a, b).As<int>();
         return Ok(result);
     }
}

额外注意事项

  • 右键项目中的example.py文件,设置复制到输出目录为「如果较新则复制」或「始终复制」,确保程序运行时能找到该文件。
  • 确认路径的正确性:ASP.NET Core运行时的当前目录可能和项目开发目录不同,建议使用绝对路径避免问题。

内容的提问来源于stack exchange,提问作者Nawapol R.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 18:57:43