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 and System Diagnostics 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 and System Diagnostics.

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

The System.Diagnostics namespace provides classes that allow you to interact with system processes, event logs, and performance counters.

Using Iron Python

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(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonSampleIronPython.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("From Iron Python");
    Console.WriteLine("5 + 10 = {0}", calculatorInstance.add(5, 10));
    Console.WriteLine("5++ = {0}", calculatorInstance.increment(5));
}

Output:

From Iron Python

5 + 10 = 15

5++ = 6

Using System Diagnostics

Step 1: Create a project in Visual Studio

Same as above in Iron Python method

Step 2: Create a python script

import sys

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

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

#creating object of class
calculatorObj = calculator()
#capturing input from command line and casting to integer
x = int(sys.argv[1])
y = int(sys.argv[2])
z = calculatorObj.add(x, y)
#printing result on console
print(z)

Step 3: Execute script using System Diagnostics

static void Main(string[] args)
{
    System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo();
    //python interprater location
    start.FileName = @"C:\Users\nikhiljo\AppData\Local\Programs\Python\Python37-32\python.exe";
    //argument with file name and input parameters
    start.Arguments = string.Format("{0} {1} {2}", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonSampleSystemDiagnostic.py"), 5, 10);
    start.UseShellExecute = false;// Do not use OS shell
    start.CreateNoWindow = true; // We don't need new window
    start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
    start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
    start.LoadUserProfile = true;
    using (System.Diagnostics.Process process = System.Diagnostics.Process.Start(start))
    {
        using (StreamReader reader = process.StandardOutput)
        {
            string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
            string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
            Console.WriteLine("From System Diagnostics");
            Console.WriteLine("5 + 10 = {0}", result);
        }
    }

    Console.ReadLine();
}

Output:

From System Diagnostics

5 + 10 = 15

Conclusion

    You can use both of the approaches to execute python script only difference IronPython is light weighted interpreter which may not be able to run script which uses complex 3rd party packages and setup may be difficult sometimes but capturing results are very easy. Other hand System Diagnostics uses python interpreter which is installed on machine and automatically takes advantages of 3rd party packages installed on machine but it may get slow and capturing results may become challenging.


Like 1 Person
Last modified on 1 September 2019
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 133
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 1 Person on 12 August 2019
Nikhil Joshi

Hi Lee,

Will extend this article soon to provide one more way to invoke python script using System Diagnostics. But for your question you can simply pass python function name in "GetVariable" method and call it like:

var main = scope.GetVariable("main");
var result = main();

Thanks

Like 0 People on 26 August 2019
Nikhil Joshi

Hi Lee,

Please check the article, I have updated it.

Thanks,

Nikhil

Like 0 People on 1 September 2019
Manju

Thanks! It's helpful 

Like 1 Person on 25 September 2019

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

Existing User

Login via:

New User



x