Home > Article > Backend Development > C# implements calling Python module
This article mainly introduces the method of calling Python module in C# in detail, which has certain reference value. Interested friends can refer to it
At present, C# and Python are relatively popular. Computer programming languages have their own advantages and disadvantages. It would be a wonderful thing if they could work together. Today I will explain how to use C# to call Python.
If C# supports calling Python modules, we first need to install some extensions. It is recommended to use the IronPython library here.
The first step, We need to download the installation package of the IronPython library. Here, please go to the official website ironpython.codeplex.com/ to download and install the relevant library files.
The second step, We create a new C# console test project and add the following DLL in the IronPython installation directory File added to projectReference.
The third step, We write C# code separately and add Python code files to the project, the code is as follows.
C# code part
using System; using IronPython.Hosting; //导入IronPython库文件 using Microsoft.Scripting.Hosting; //导入微软脚本解释库文件 namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ScriptRuntime pyRuntime = Python.CreateRuntime(); //创建一下运行环境 dynamic obj=pyRuntime.UseFile("debug.py"); //调用一个Python文件 int num1, num2; Console.Write("Num1:"); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Num2:"); num2 = Convert.ToInt32(Console.ReadLine()); int sum = obj.add(num1, num2); //调用Python文件中的求和函数 Console.Write("Sum:"); Console.WriteLine(sum); } } }
Python code part
def add(num1,num2): return num1+num2;
You need to modify the Python file in the project when compiling AttributesAs shown below, otherwise the file will be reported Unable to locate the error, the running result is as shown on the right.
Through the above experimental process, you can easily use C# to call Python files, but I don’t know if you will have the same doubts as me, how to What about packaging C# executable programs and Python files? If it is a simple compression, the library files required for running may be missing. If you also have questions about this, please pay attention to the next article on the blog: Using Visual Studio to find the necessary runtime library files for the program.
【Related Recommendations】
1. Special Recommendation: "php Programmer Toolbox" V0.1 version download
3. Li Yanhui ASP Basic Video Tutorial
The above is the detailed content of C# implements calling Python module. For more information, please follow other related articles on the PHP Chinese website!