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

ASP.NET C#调用Python机器学习代码报No module named pandas错误问询

问题根因
  • 你通过pip安装的pandas、scikit-learn均为适配官方CPython运行环境的版本,依赖大量C语言扩展实现,而IronPython是基于.NET runtime的Python实现,原生不支持CPython的C扩展库,哪怕路径配置正确也无法加载这类库。
  • 你当前代码中仅添加了CPython的根目录到IronPython的搜索路径,未添加对应Lib\site-packages目录,即便库兼容也会无法找到安装的第三方包。
可行解决方案

方案一(推荐):替换IronPython为进程调用标准CPython执行脚本

该方案无需修改你现有的Python代码逻辑,直接复用已经安装好pandas、scikit-learn的CPython环境运行,稳定性最高。

修改后的C#代码

using System;
using System.Diagnostics;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int var1 = 0;
            int var2 = 0;
            ProcessStartInfo pythonStartInfo = new ProcessStartInfo
            {
                // 填写你本地CPython的python.exe完整路径
                FileName = @"C:\Users\humay\AppData\Local\Programs\Python\Python310\python.exe",
                // 传入脚本路径和需要的参数
                Arguments = $@"C:\Users\humay\Downloads\python.py {var1} {var2}",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            using (Process pythonProcess = Process.Start(pythonStartInfo))
            {
                // 读取Python脚本的输出结果
                string result = pythonProcess.StandardOutput.ReadToEnd();
                string errorInfo = pythonProcess.StandardError.ReadToEnd();
                pythonProcess.WaitForExit();

                Console.WriteLine("分类结果:");
                Console.WriteLine(result);
                if (!string.IsNullOrEmpty(errorInfo))
                {
                    Console.WriteLine("执行错误:");
                    Console.WriteLine(errorInfo);
                }
            }
        }
    }
}

补充Python代码修改

在你现有的Python代码末尾添加以下内容,接收C#传入的参数并调用目标函数:

import sys
if __name__ == "__main__":
    # 按顺序读取传入的参数,按需转换类型
    var1 = int(sys.argv[1])
    var2 = int(sys.argv[2])
    test_func(var1, var2)

方案二(不推荐):适配IronPython运行环境

你需要完全重写Python代码,移除所有依赖C扩展的第三方库:

  • 用Python内置的csv模块替代pandas读取iris数据集
  • 自行实现高斯朴素贝叶斯分类、数据标准化的逻辑,不能使用scikit-learn的相关接口
    修改完成后将CPython的Lib\site-packages路径添加到IronPython的搜索路径即可运行,该方案改造成本极高,仅适合必须嵌入.NET运行的场景。

内容的提问来源于stack exchange,提问作者chicacherry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:45:03