Pythonnet importing python script into c#

176 views Asked by At

I am trying to import a script as follows:

        Runtime.PythonDLL = "python311.dll";
        PythonEngine.Initialize();

        using (Py.GIL())
        {
            var script = Py.Import("example");
            var result = script.InvokeMethod("foo");
        }

The script is as follows:

def foo():
   return 1

It is located in a folder called example in the site-packages folder of python. The example folder also has an empty init.py file.

When I run the above C# code, I get the following error: Python.Runtime.PythonException: 'module 'example' has no attribute 'foo''

Any help would be greatly appreciated.

2

There are 2 answers

2
robotrage On
using Python.Runtime;

// Initialize the Python engine
PythonEngine.Initialize();

// Load the Python script
dynamic script = PythonEngine.ModuleFromString("example", File.ReadAllText("example.py"));
// We call the Python function
dynamic output = script.foo();

// Print the resule in the console.
Console.WriteLine(output);  

(untested)

https://www.educative.io/answers/how-to-call-a-python-function-from-c-sharp

0
Revolution88 On

You need to add path to your py files like:

 dynamic sys = Py.Import("sys");
 sys.path.append("../path_to_py_files/");

After that you can try your code:

 dynamic script = Py.Import("example");
 dynamic result = script.InvokeMethod("foo");