Creating Python Modules from CSharp

This recipe is intended for use with IronPython 2 / 2.0.1. It may also work with IronPython 2.6. (Leave a note on this page if you try it.)

Sometimes you want to write C# code that interacts with IronPython and has access to the current engine. Instead of attempting to get access to the current engine directly you create methods that take a CodeContext.

When your methods are called IronPython will automatically pass in the CodeContext for you. From this you can get access to a Python specific LanguageContext: PythonContext python = PythonContext.GetContext(context);.

This provides many of the features of the ScriptEngine, including allowing us to create new classes and modules, without needing direct access to the current engine.

This code example creates and returns a new Python module by executing a snippet of IronPython code. All the work is done in the CreateModule static method.

using System; using System.Collections.Generic; using System.Text;

using IronPython.Hosting; using IronPython.Runtime; using IronPython.Runtime.Types;

using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using Microsoft.Scripting.Runtime;

namespace ExecutePython {   public class ExecutePython {       static string code = @" class Foo(object):    attribute = 'weeeee'

";       public static Scope CreateModule(CodeContext context)        {            PythonContext python = PythonContext.GetContext(context);

PythonDictionary globals = new PythonDictionary; globals["__name__"] = "AModule"; Scope module = new Scope(globals); SourceUnit script = python.CreateSnippet(code, SourceCodeKind.Statements); script.Execute(module); return module; }   } }

It would be used from IronPython like this: from ExecutePython import ExecutePython module = ExecutePython.CreateModule

instance = module.Foo

Unfortunately there is a problem with using this code on Silverlight. It basically works but Python code that is executed is unable to import from the xap file. This looks like a bug with the Silverlight Dynamic Languages SDK, but this entry will be updated if there is any more news.

Back to Contents.