程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to run Python code in C#

編輯:Python

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#.

Then try pythonnet.

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.

Demo

1. Create a project

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

2. Initialization

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();

3. Using the Python library

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);

4. 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 classdynamic demo = demoCode.Demo();//Call the SayHello method of the Demo classConsole.WriteLine(demo.SayHello("MyIO"));

Finally, the running result is as follows:

Conclusion

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

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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved