Loading Python file in .NET and Call function

Hopefully this helps some of you out that are working with .NET core and this python.net library. The point of this sample code is to show you how to:

  • Load your custom python file
  • Execute a function that is with a class

In the program.cs (.net core 7) we can setup the startup python code. Make sure to replace yourname with your directory name: Program.cs snippet

Runtime.PythonDLL = @"C:\Users\[yourname]\AppData\Local\Programs\Python\Python39\python39.dll";
PythonEngine.Initialize();
Py.GIL();

I have a folder in my ASP.NET project that is called PythonScripts that houses my python files. For this example I use a file called usb.py that contains a class (exampleClass) with one function (sayHello). We'll call that function and get the returned string. Finally we'll convert that returned PyObject to a string in c#.

// Python file is located in a project folder called PythonScripts
string file = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\PythonScripts\usb.py";  

if (!PythonEngine.IsInitialized)// Since using asp.net, we may need to re-initialize
{
 PythonEngine.Initialize();
 Py.GIL();
}
            
using (var scope = Py.CreateScope())
            {
                string code = File.ReadAllText(file); // Get the python file as raw text
                var scriptCompiled = PythonEngine.Compile(code, file); // Compile the code/file
                scope.Execute(scriptCompiled); // Execute the compiled python so we can start calling it.
                PyObject exampleClass = scope.Get("exampleClass"); // Lets get an instance of the class in python
                PyObject pythongReturn = exampleClass.InvokeMethod("sayHello"); // Call the sayHello function on the exampleclass object
                string? result = pythongReturn.AsManagedObject(typeof(string)) as string; // convert the returned string to managed string object
            }