Home >Backend Development >Python Tutorial >How to call python in c#
If C# supports calling Python modules, we first need to install some extensions. The IronPython library is recommended here.
In the first step, we need to download the installation package of the IronPython library. Here, please go to the official website http://ironpython.codeplex.com/ to download and install the relevant library files.
Related recommendations: "Python Video Tutorial"
In the second step, we create a new C# console test project and add Add the following DLL files in the IronPython installation directory to the project reference.
The third step is to write C# code separately and add the Python code file 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;
When compiling, you need to modify the Python file attributes in the project as shown below, otherwise an error that the file cannot be located will be reported. Run The results are as shown on the right.
The above is the detailed content of How to call python in c#. For more information, please follow other related articles on the PHP Chinese website!