如何让Python.NET使用Python 3.6?我复制了下面的示例代码,当我运行它时,我得到错误:
Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'python35': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at Python.Runtime.Runtime.Py_IsInitialized()
at Python.Runtime.Runtime.Initialize()
at Python.Runtime.PythonEngine.Initialize(IEnumerable`1 args, Boolean setSysArgv)
at Python.Runtime.PythonEngine.Initialize(Boolean setSysArgv)
at Python.Runtime.PythonEngine.Initialize()
at Python.Runtime.Py.GIL()
我没有Python 3.5,因此没有python35.dll。我有Python 3.6。它是Anaconda Distribution的一部分。我如何让Python.Net使用它?
示例代码:
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
Console.WriteLine(np.cos(np.pi * 2));
dynamic sin = np.sin;
Console.WriteLine(sin(5));
double c = np.cos(5) + sin(5);
Console.WriteLine(c);
dynamic a = np.array(new List<float> { 1, 2, 3 });
Console.WriteLine(a.dtype);
dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
Console.WriteLine(b.dtype);
Console.WriteLine(a * b);
Console.ReadKey();
}
更新以回答评论中的问题: 我通过获取NuGet包“pythonnet_py35_dotnet”来安装Python.net它的版本是v2.3.0。
python -c“import sys; print(sys.version)”给出
3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]
“其中python”给出了
C:\Users\<username>\AppData\Local\Continuum\Anaconda3\python.exe
答案 0 :(得分:1)
对我来说可行的解决方案是:
*考虑到我正在使用Visual Studio 2012 Express,
Python.Runtime.dll
的引用(如果您难以轻松找到DLL文件,只需尝试在Windows上使用Everything应用)在C#代码顶部添加以下行。
using Python.Runtime;
在调用using (Py.GIL()){...}
Environment.SetEnvironmentVariable("PATH", @"path-to-the-directory-containing-python-interpreter.exe", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONHOME", @"path-to-the-directory-containing-python-interpreter.exe", EnvironmentVariableTarget.Process);
最后,最重要的事情是在“解决方案资源管理器”的“属性”的“构建”选项卡中设置系统架构类型。
就我而言(不使用虚拟环境),就像下面的图片一样:
希望它能起作用!