How to get Python.Net to use Python 3.6 Anaconda Distribution

2

How do I get Python.NET to use Python 3.6? I copied the sample code below and when I run it I get the error:

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()

I don't have Python 3.5 and thus no python35.dll. I have Python 3.6. It's part of the Anaconda Distribution. How do I get Python.Net to use that?

The sample code:

    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();
    }

Update to answer questions in the comments: I installed Python.net by getting the NuGet package "pythonnet_py35_dotnet" It's version is v2.3.0.

python -c "import sys; print (sys.version)" gives

3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]

"where python" gives

C:\Users\<username>\AppData\Local\Continuum\Anaconda3\python.exe
python
python.net
asked on Stack Overflow Aug 24, 2017 by DigitalEd • edited Aug 25, 2017 by DigitalEd

1 Answer

0

The working solution for me is:

*Consider I'm using Visual Studio 2012 Express,

  1. Add a reference to Python.Runtime.dll in References in Solution Explorer(if you have trouble finding the DLL file easily, just try using Everything app on windows)
  2. Add the following line at the top of your C# code.

    using Python.Runtime;
    
  3. Add the following code before calling 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. Finally, the most important thing is to set your system architecture type in the Build tab of the Properties is Solution Explorer.

In my case(not using virtual environments), it's like the following pictures:

Steps 1 to 3.

Step 4.

Hope it works!

answered on Stack Overflow Aug 25, 2019 by AK47dev

User contributions licensed under CC BY-SA 3.0