IronPython C# Integration

1 - Basics

Introduction

This tutorial shows how Python scripts can be embedded into C# code using IronPython. We will only cover Python 2 because at the time of writing IronPython support for Python 3 is still being worked on.

Contents overview

The tutorial is spread over four pages.

  • On page 1 (this page) we will show two examples of how Python scripts that don't depend on any modules can be executed from C# code.
  • On page 2 we will show how to execute scripts that depend on modules.
  • On page 3 we will show how data can be shared between the C# code and the Python script.
  • On page 4 we will show how Python modules can be imported in such a way that their contents can be accessed directly from C# code.

Prerequisites

We assume the reader knows how to write C# console applications. Throughout this tutorial we will use Visual Studio 2019 to write and run our C# applications.

We also assume the reader is familiar with Python 2.

Executing a Python script from C#

First example

The first example shows how to execute Python code from C# using IronPython. For simplicity the Python script is just hardcoded as a string in the C# code. We will also show how to use NuGet to add IronPython to the C# project.

We start by creating a C# console application project in Visual Studio 2019. We call this application PythonScriptExecution1. The full example is available from our GitHub repository: IronPythonTutorials/CSharpIntegration/PythonScriptExecution1.

We then use the NuGet package manager to search for the IronPython package and add it to our project as shown on Figure 1. Note that there are several IronPython packages that show up in the list: for this example we only need the one named "IronPython".

Get IronPython with NuGet
Figure 1: Get IronPython with NuGet

This will add the following assemblies to the project:

  • IronPython.2.7.4\lib\Net45\IronPython.dll
  • IronPython.2.7.4\lib\Net45\IronPython.Modules.dll
  • IronPython.2.7.4\lib\Net45\IronPython.SQLite.dll
  • IronPython.2.7.4\lib\Net45\IronPython.Wpf.dll
  • IronPython.2.7.4\lib\Net45\Microsoft.Dynamic.dll
  • IronPython.2.7.4\lib\Net45\Microsoft.Scripting.dll
  • IronPython.2.7.4\lib\Net45\Microsoft.Scripting.AspNet.dll
  • IronPython.2.7.4\lib\Net45\Microsoft.Scripting.Metadata.dll

For this first example we invoke a Python script that will simply print "Hello World!" on the console. To keep it as simple as possible we simply hardcode the Python code inside a string and use CreateScriptSourceFromString to create the Microsoft.Scripting.Hosting.ScriptSource instance from it. As you can see this is really easy to do and only takes 3 lines of code.

 File: Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PythonScriptExecution1
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = 
                IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = 
                pythonEngine.CreateScriptSourceFromString("print 'Hello World!'");
            pythonScript.Execute();
        }
    }
}

Running the program generates the following output on the console.

 Console output
Hello World!
Press any key to continue . . .

Second example

The second example is almost identical to the first one but we will use the CreateScriptSourceFromFile function to load the script from a file instead of hardcoding it in a string.Since we put the script in the same directory as the Program.cs file we need to go up two directories when executing the program from Visual Studio. This is why the path to our script is ..\\..\\HelloWorld.py". You could of course just put the script in the same directory as the executable.The code is shown below. When executing the program the output is of course identical to our previous example.

The full example is available from our GitHub repository: IronPythonTutorials/CSharpIntegration/PythonScriptExecution2.

 File: Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PythonScriptExecution2
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = 
                IronPython.Hosting.Python.CreateEngine();
            // We execute this script from Visual Studio 
            // so the program will be executed from bin\Debug or bin\Release
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = 
                pythonEngine.CreateScriptSourceFromFile("..\\..\\HelloWorld.py");
            pythonScript.Execute();
        }
    }
}

And here is the Python script.

 File: HelloWorld.py
print 'Hello World!'