Serge Weinstock
Serge Weinstock

Reputation: 1501

Pythonnet: how to use an embedded python intepreter?

I'm trying to use an embedded python interpreter from C# using pythonnet (the python3 compatible version found at https://github.com/renshawbay/pythonnet)

My interpreter is located in D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime and has the "Lib" and "Libs" folder from the python distribution.

I've tested using the following code:

   <!-- language: c# -->
   PythonEngine.PythonHome = @"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
   PythonEngine.ProgramName = "PythonRuntime";
   PythonEngine.Initialize();
   using (Py.GIL())
   {
      PythonEngine.RunSimpleString("print(1)");
   }

But, it doesn't work. I get a "SystemError: PyEvalCodeEx: NULL globals". Everytime I try to get an object from python, the code fails.

What am I doing wrong?

Upvotes: 2

Views: 2941

Answers (1)

Serge Weinstock
Serge Weinstock

Reputation: 1501

I think I've found the answer. If I add a reference to the "clr" module provided by pythonnet, it does work

PythonEngine.PythonHome = @"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
PythonEngine.ProgramName = "PythonRuntime";
PythonEngine.Initialize();
// ==>
PyObject a = PythonEngine.ImportModule("clr");
using (Py.GIL())
{
    PythonEngine.RunSimpleString("print(1)");
}

Upvotes: 1

Related Questions