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

版本对应关系

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”

使用流程


            string dllPath = @"C:\Program Files\Python38\python38.dll";            
            string pythonHomePath = @"C:\Program Files\Python38";
          
            // 对应python内的重要路径
            string[] py_paths = {"DLLs", "lib", "lib\\site-packages", "lib\\site-packages\\win32"
                , "lib\\site-packages\\win32/lib", "lib\\site-packages\\Pythonwin" };
            string pySearchPath = $"{pythonHomePath};";
            foreach (string p in py_paths)
            {
                pySearchPath += $"{pythonHomePath}\\{p};";
            }

            // 此处解决BadPythonDllException报错
            Runtime.PythonDLL = dllPath;
            Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", dllPath);
            // 配置python环境搜索路径解决PythonEngine.Initialize() 崩溃
            PythonEngine.PythonHome = pythonHomePath;
            PythonEngine.PythonPath = pySearchPath;

            PythonEngine.Initialize();

            
            string position = "";
            using (Py.GIL())
            {
                string code = File.ReadAllText(@"E:\main.py");
                var scriptCompiled = PythonEngine.Compile(code, "");                
                dynamic test = Py.CreateScope();
                test.Execute(scriptCompiled);              
                dynamic r1 = test.replace("Init Python"); //OK
                // Console.WriteLine(r1);
                Debug.LogError("Init Python");
                position = (string) r1;
            }
            
            PythonEngine.Shutdown();

数据类型的对应

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

//or

 

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

你可能感兴趣的:(python,C#,pythonnet,python,c#)