private void TestPython(){try{//python环境路径string pathToVirtualEnv = @"H:\ProgramData\anaconda3\envs\python39";Environment.SetEnvironmentVariable("PATH", pathToVirtualEnv, EnvironmentVariableTarget.Process);Environment.SetEnvironmentVariable("PYTHONHOME", pathToVirtualEnv, EnvironmentVariableTarget.Process);Environment.SetEnvironmentVariable("PYTHONPATH", pathToVirtualEnv + "\\Lib\\site-packages;" + pathToVirtualEnv + "\\Lib", EnvironmentVariableTarget.Process);PythonEngine.PythonHome = pathToVirtualEnv;PythonEngine.PythonPath = PythonEngine.PythonPath + ";" + Environment.GetEnvironmentVariable("PYTHONPATH", EnvironmentVariableTarget.Process);PythonEngine.Initialize();PythonEngine.BeginAllowThreads();using (Py.GIL()) // 使用这个来包裹你调用python方法的代码{// 先引入python模块,也就是我们上面生成的pyd文件,如Test.cp39-win_amd64.pyddynamic my_module = Py.Import("Test");// Call your python functions.int value = my_module.ShowNum();Debug.Write("[Debug]:" + value +"\t\n");}}catch (Exception ex){Debug.WriteLine("[ERROR]:" + ex.Message + "\t\n");}}
注意:pythonnetd 版本与Python的版本需要一致