Embedding a Python Interpreter in C# – Iron Python

I needed to be able to execute scripts in two client applications. One was written in Java the other in C#.
The script needs to manipulate classes in the language the interpreter in embedded in.

This program works with IronPython 2.7.

You need to reference
IronPython, IronPython.Modules, Microsoft.Scripting and Microsoft.Scripting.Core

The example below is a simple test – it loads a string with a script in in and then makes use of it
(Note Test Class in this case is a simple c# class with a property (string) Value):

using System;
using System.Collections.Generic;
using System.Reflection;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace EmbeddedPython
{
  class Program
  {
    static void Main(string[] args)
    {
        ScriptEngine _eng = 
           Python.CreateEngine((Dictionary<string,object>)null);

        _eng.Runtime.LoadAssembly(
        Assembly.GetAssembly(typeof(EmbeddedPython.Program))
      );

      ScriptScope scope = _eng.CreateScope();
//this is our python program as a string
      string importText = @"
from EmbeddedPython import TestClass

def MakeOne():
  return TestClass()

def Update(item):
  item.Value = ""Hello World"" 
";

      _eng.CreateScriptSourceFromString(
        importText,                                    
        SourceCodeKind.Statements
      ).Execute(scope);

      Func<TestClass> makeOne = 
          scope.GetVariable<Func<TestClass>>("MakeOne");

      Action<TestClass> update = 
          scope.GetVariable<Action<TestClass>>("Update");

      TestClass instance = makeOne();
      update(instance);

      Console.WriteLine(instance.Value);

    }
  }
}

This entry was posted in Python and tagged , , . Bookmark the permalink.

Leave a Reply