• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

C#使用pythonnet调用python代码过程

武飞扬头像
leeyunj
帮助1

版本对应关系

pythonnet 版本3.0.1,python版本3.8.

  1. 如果使用python3.10,会出现报错python310.dll. ---> System.ComponentModel.Win32Exception: 找不到指定的模块

  1. Net程序使用64位,如果使用anyCPU或者32位,会出现Python.Runtime.BadPythonDllException:“Runtime.PythonDLL was not set or does not point to a supported Python runtime DLL. See https://github.com/pythonnet/pythonnet#embedding-python-in-net

使用流程

  1.  
     
  2.  
    string dllPath = @"C:\Program Files\Python38\python38.dll";
  3.  
    string pythonHomePath = @"C:\Program Files\Python38";
  4.  
     
  5.  
    // 对应python内的重要路径
  6.  
    string[] py_paths = {"DLLs", "lib", "lib\\site-packages", "lib\\site-packages\\win32"
  7.  
    , "lib\\site-packages\\win32/lib", "lib\\site-packages\\Pythonwin" };
  8.  
    string pySearchPath = $"{pythonHomePath};";
  9.  
    foreach (string p in py_paths)
  10.  
    {
  11.  
    pySearchPath = $"{pythonHomePath}\\{p};";
  12.  
    }
  13.  
     
  14.  
    // 此处解决BadPythonDllException报错
  15.  
    Runtime.PythonDLL = dllPath;
  16.  
    Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", dllPath);
  17.  
    // 配置python环境搜索路径解决PythonEngine.Initialize() 崩溃
  18.  
    PythonEngine.PythonHome = pythonHomePath;
  19.  
    PythonEngine.PythonPath = pySearchPath;
  20.  
     
  21.  
    PythonEngine.Initialize();
  22.  
     
  23.  
     
  24.  
    string position = "";
  25.  
    using (Py.GIL())
  26.  
    {
  27.  
    string code = File.ReadAllText(@"E:\main.py");
  28.  
    var scriptCompiled = PythonEngine.Compile(code, "");
  29.  
    dynamic test = Py.CreateScope();
  30.  
    test.Execute(scriptCompiled);
  31.  
    dynamic r1 = test.replace("Init Python"); //OK
  32.  
    // Console.WriteLine(r1);
  33.  
    Debug.LogError("Init Python");
  34.  
    position = (string) r1;
  35.  
    }
  36.  
     
  37.  
    PythonEngine.Shutdown();
学新通

数据类型的对应

string[] mylist = (string[])pyList;

//or

List<string> mylist = ((string[])pyList).ToList<string>();

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfkbhh
系列文章
更多 icon
同类精品
更多 icon
继续加载