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
    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));


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

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);



From System Diagnostics

5 + 10 = 15


    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: 164
Questions: 16
Given Best Solutions: 16 *


Lee Williams

HI Nikhil

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



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();


Like 0 People on 26 August 2019
Nikhil Joshi

Hi Lee,

Please check the article, I have updated it.



Like 0 People on 1 September 2019

Thanks! It's helpful 

Like 1 Person on 25 September 2019
Grant Gualtieri

Hi Nikhil,

Would you be able to provide any insight about how to use third party python modules using the Systems Diagnostics process?

Like 1 Person on 4 December 2020
Nikhil Joshi

Hi Grant,

Thanks for reaching out. You will have to install modules using pip and import that in script you are trying to run. This is how you can use any 3rd party module.

Suppose you are deploying your script on AWS VM then your deployment script should already run pip install for required modules and then you will be able to run your main script using system diagnostic.


Like 1 Person on 6 December 2020
Yusuf Sönmez

Hello. Thank for content. I would like to ask something. If i want to use some result from python script how can i do this? For example if i want to insert to database the data which i get from python?

Like 0 People on 2 December 2021
Nikhil Joshi

Hi Yusuf,

As mentioned in system diagnostic section. I'm printing the results. You can simply write results to a file and after that read the file and insert data into database.

Like 0 People on 2 December 2021

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

Existing User

Login via:

New User