繁体   English   中英

如何让 Python.Net 使用 Python 3.6 Anaconda Distribution

[英]How to get Python.Net to use Python 3.6 Anaconda Distribution

如何让 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 发行版的一部分。 我如何让 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)]

“蟒蛇在哪里”给出

C:\Users\<username>\AppData\Local\Continuum\Anaconda3\python.exe

对我来说工作的解决方案是:

*考虑到我使用的是 Visual Studio 2012 Express,

  1. 在解决方案资源管理器的 References 中添加对Python.Runtime.dll的引用(如果您无法轻松找到 DLL 文件,请尝试在 Windows 上使用Everything应用程序)
  2. 在 C# 代码的顶部添加以下行。

     using Python.Runtime;
  3. 在调用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);
  4. 最后,最重要的是在解决方案资源管理器属性的构建选项卡中设置您的系统架构类型。

在我的情况下(不使用虚拟环境),就像下图:

步骤 1 到 3。

第 4 步。

希望它有效!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM