- Notifications
You must be signed in to change notification settings - Fork748
Loading Python file in .NET and Call function
exzile edited this pageFeb 1, 2023 ·2 revisions
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 PythonScriptsstringfile=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(varscope=Py.CreateScope()){stringcode=File.ReadAllText(file);// Get the python file as raw textvarscriptCompiled=PythonEngine.Compile(code,file);// Compile the code/filescope.Execute(scriptCompiled);// Execute the compiled python so we can start calling it.PyObjectexampleClass=scope.Get("exampleClass");// Lets get an instance of the class in pythonPyObjectpythongReturn=exampleClass.InvokeMethod("sayHello");// Call the sayHello function on the exampleclass objectstring?result=pythongReturn.AsManagedObject(typeof(string))asstring;// convert the returned string to managed string object}