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#.
Then try pythonnet
.
pythonnet
can integrate Python code to run in the Common Language Runtime (CLR) of .NET 4.0+.
It should be noted that it does not compile Python code into IL code, but integrates Python's CPython engine with the .NET runtime to ensure that the CLR can use existing Python code and C-API extensions, whileMaintain native execution speed of Python code.
Create a console project that references the pythonnet Nuget package.
Note that "Include pre-releases" must be checked to see officially maintained Nuget packages:
Python 3 needs to be installed on the computer
You need to set the Runtime.PythonDLL
property first, otherwise the program will throw 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();
All calls to python must be within 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 (which needs to be pip install):
dynamic np = Py.Import("numpy");Console.WriteLine(np.pi);
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 classdynamic demo = demoCode.Demo();//Call the SayHello method of the Demo classConsole.WriteLine(demo.SayHello("MyIO"));
Finally, the running result is as follows:
With pythonnet
, running Python code in C# is as easy as that!
Add WeChat [MyIO666] to invite you to join the technical exchange group