Executing Python Script from C#

Passing parameters to Python method and capturing return values from C#, Calling Python method from C#


Category: .net Framework Tags: C#, Python

Iron Python Code Files

    For some developers, python is enough to fulfill their needs but in some cases, you might need python script to be called from any compiled programming language i.e. C#, Java, C++. In this article, I’m going to show you how easy to execute a python script from C# using IronPython.

IronPython is an open-source library to integrate python with .net programming languages. IronPython can use the .NET Framework and Python libraries, and other .NET languages can use Python code just as easily.

Step 1: Create a project in Visual Studio

 

Creating Console Application in C#
Fig 1: Creating Console Application in C#


Step 2: Install IronPython from NuGet

 

IronPython NuGet
Fig 2: IronPython NuGet

 

Step 3: Create Python file

class calculator:
    def add(self, x, y):
        return x + y

    def increment(self, x):
        x += 1;
        return x;

Step 4: Using Python Engine in C#

static void Main(string[] args)
{
    //instance of python engine
    var engine = Python.CreateEngine();
    //reading code from file
    var source = engine.CreateScriptSourceFromFile(AppDomain.CurrentDomain.BaseDirectory + "PythonSample.py");
    var scope = engine.CreateScope();
    //executing script in scope
    source.Execute(scope);
    var classCalculator = scope.GetVariable("calculator");
    //initializing class
    var calculatorInstance = engine.Operations.CreateInstance(classCalculator);
    Console.WriteLine("5 + 10 = {0}",calculatorInstance.add(5,10));
    Console.WriteLine("5++ = {0}", calculatorInstance.increment(5));
    Console.ReadLine();
}

Output:

5 + 10 = 15

5++ = 6


Like 1 Person
Last modified on 11 October 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 132
Questions: 9
Given Best Solutions: 9 *

Comments:

Lee Williams

HI Nikhil

How do i call a def main() function in Python and capture an output variable?

Cheers

Lee

Like 0 People about 11 days ago

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x