pythonnet Embedding Python in .net example failing to load module

跟風遠走 提交于 2019-12-22 11:31:17

问题


I'm trying to run the Embedding Python in .NET example from https://github.com/pythonnet/pythonnet. I've followed troubleshooting articles to set the proper %PYTHONPATH% and %PYTHONHOME% to my anaconda environment in the program base directory.

After activating my anaconda environment, I have successfully imported sys, and imp as a test, and also sucessfully used PythonEngine.RunSimpleString(), but the numpy example fails with Python.Runtime.PythonException: ImportError : No module named 'numpy'

importing numpy from python in this environment was successful, but this and other packages fail to import in pythonnet.

Pythonnet version: 2.3 x64 (installed using conda install -c pythonnet pythonnet)

Python version: Python 3.5 x64 (anaconda)

Operating System: Windows 10

The following code produces the error:

static void Main(string[] args)
{
    string envPythonHome = AppDomain.CurrentDomain.BaseDirectory + "cntk-py35";
    string envPythonLib = envPythonHome + @"\Lib";
    Environment.SetEnvironmentVariable("PYTHONHOME", envPythonHome, EnvironmentVariableTarget.Process);
    Environment.SetEnvironmentVariable("PATH", envPythonHome + ";" + Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine), EnvironmentVariableTarget.Process);
    Environment.SetEnvironmentVariable("PYTHONPATH", envPythonLib, EnvironmentVariableTarget.Process);

    PythonEngine.PythonHome = envPythonHome;
    PythonEngine.PythonPath = Environment.GetEnvironmentVariable("PYTHONPATH");

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

It seems that any package under site-packages in my environment similarly fail. Adding to %PATH% did not work. Is there a way to get pythonnet to recognize and load these modules?


回答1:


I was able to import the modules by adding Lib/site-packages to the PYTHONPATH variable (rather than the PATH) which adds the folder to sys.path. It was necessary for any other python libraries and custom python code to add the corresponding folder to PYTHONPATH.



来源:https://stackoverflow.com/questions/47559658/pythonnet-embedding-python-in-net-example-failing-to-load-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!