How to call python code in c# applications

Posted on July 2, 2019
python
c#
IronPython
1862

.net supports 98 languages as a whole and python is one of the scripting language among all.In this article i will demonstrate how to call a python program from c# application.I do not want to go much deep into the theory, i will just show you hands-on.This will be helpful to the people who already have atleast some knowledge on c# as well as on python.

Steps:

a)create one python file named pythonNetC.py and add the below content to the file

class Calculator:
    def add(self,argsA,argsB):
        return argsA+argsB
    def sub(self,argsA,argsB):
        return argsA-argsB

 

b)Create one console application project.

c)Add the created pythonNetC.py to the project as Existing item.(Right click on project->Add Existing Item->Give the path of the python file where you created).

d)To run the python files we need to have python engine. that will come by adding IronPython dll from Manage Nuget Packages, available on right click on the project.

  

e)Try to check in the references section whether the IronPython related modules have been added or not?

f)On successfull addition , try to add the execution code in Main.cs

using System.Text;
using System.Threading.Tasks;
using IronPython.Hosting;

namespace PythonNet
{
    class Program
    {
        static void Main(string[] args)
        {
            var Engine = Python.CreateEngine();
            dynamic py = Engine.ExecuteFile("C:\\Users\\harika\\source\\repos\\Day6\\PythonNet\\pythonNetC.py");
            dynamic calc = py.Calculator();
            Console.WriteLine(calc.__class__.__name__);
            double num1 = 5;
            double num2 = 3;
            double sum = calc.add(num1, num2);
            double sub = calc.sub(num1, num2);
            Console.WriteLine("{0}+{1}={2}", num1, num2, sum);
            Console.WriteLine("{0}-{1}={2}", num1, num2, sub);
        }
    }
}

g)Try to run the application by pressing ctrl+F5 (Without debugging), You can be able to see the output on clr.




0 comments

Please log in to leave a comment.