How to run Python code in C#

thumbnail

foreword

Python is a powerful programming language. In particular, it also has numerous great libraries (such as numPy, sciPy, pandas, etc.) that can significantly simplify and speed up development. So when it comes to solving some problems, implementing it in Python might be the best way to go!

However, we also want the code to run in C#.

Well, try pythonnet.

pythonnet

pythonnet can integrate Python code to run in the Common Language Runtime (CLR) of .NET 4.0+.

Note that instead of compiling Python code to IL code, it integrates Python's CPython engine with the .NET runtime to ensure that the CLR can use existing Python code and C-API extensions while maintaining Python code the native execution speed.

Demo 1. Create a project

Create a console project that references the pythonnet Nuget package.

Note that you must check " Include pre-releases " to see the officially maintained Nuget packages:

Python 3 needs to be installed on the computer

  1. Initialize

You need to set the Runtime.PythonDLL property first, otherwise the program will throw a BadPythonDllException:

The specific file location corresponds to the Python version and folder you installed:

Runtime.PythonDLL = Path.Combine(Environment.GetFolderPath(

Environment.SpecialFolder.LocalApplicationData),

@ "Programs\Python\Python310\python310.dll");

PythonEngine.Initialize;

  1. Using Python Libraries

All calls to python must be in a using (Py.GIL) block.

After importing the python module using Py.Import, you can call the corresponding function normally:

Here, we use the numpy library (need to have pip install):

dynamic np = Py.Import( "numpy");

Console.WriteLine(np.pi);

  1. Using Python scripts

We can also execute Python script code.

First, create the DemoCode.py file, which defines the Demo class and the SayHello method. The code is as follows:

class Demo:

def SayHello(self, name):

return"Hello "+ name

The calling code is as follows:

dynamic demoCode = Py.Import( "DemoCode");

//Instantiate the Demo class

dynamic demo = demoCode.Demo;

//Call the SayHello method of the Demo class

Console.WriteLine(demo.SayHello( "MyIO"));

Finally, the running result is as follows:

in conclusion

With pythonnet, running Python code in C# is as easy as that!

Add WeChat [MyIO666], invite you to join the technical exchange group

Latest Programming News and Information | GeekBar

Related Posts