How to call python code in c# applications

Posted on July 2, 2019

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


a)create one python file named 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 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\\");
            dynamic calc = py.Calculator();
            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.


Please log in to leave a comment.