Blake O'Hare .com

IronPython in Silverlight 2.0 and Higher

IronPython was introduced to Silverlight back in the Silverlight 1.0 days. For the first time, people could run Python-based applications in their browser. People got excited and wrote many tutorials on how to do this and posted them online. However, Silverlight 1.0 was unfortunately based on JavaScript and bears no resemblance to any modern version of Silverlight afterwards and now the internet is polluted with ancient JavaScript+Silverlight+Python tutorials.

So as a public service, I'm adding a simple and to-the-point getting-started tutorial for IronPython in Silverlight 2.0 and higher using C#.

Step 1:

Create your C#-based Silverlight Project in Visual Studio.

Step 2:

Download the IronPython binaries. It's a lovely zip file. In this file navigate to IronPython-2.7/Silverlight/bin. You'll see 5, lovely DLLs. We are interested in these.

Step 3:

Add these DLLs to your project. Add a reference. This primarily adds access to the IronPython namespace to your project. Also add a reference to Microsoft.CSharp.dll.

Step 4:

Somewhere in your code, create an IronPython engine:
Microsoft.Scripting.Hosting.ScriptEngine engine = IronPython.Hosting.Python.CreateEngine();

Step 5:

Somewhere after that, create a ScriptScope.
Microsoft.Scripting.Hosting.ScriptScope scope = engine.CreateScope();

Step 6:

Write some Python code! You can now execute Python code as a string off the Execute method from the engine. Be sure to pass in the same scope each time you do this.
engine.Execute("a = 1 + 1");

Feel free to pass in strings that are multiple lines.

To actually communicate with your Python engine, you can set and read variables in the scope. Here's a more end-to-end example:
Microsoft.Scripting.Hosting.ScriptEngine engine = IronPython.Hosting.Python.CreateEngine();
Microsoft.Scripting.Hosting.ScriptScope scope = engine.CreateScope();

scope.SetVariable("foo", 42);

    "reallyHugeNumber = foo ** foo\n" +
    "stringOfBigNumber = str(reallyHugeNumber)\n" + 
    "lastFourDigits = int(stringOfBigNumber[-4:])",

int lastFourDigits = (int)scope.GetVariable("lastFourDigits");

This is enough to get you started. In reality, you'll probably want to do something more complex. For example, if you have Python code that spins in a while loop that you want to communicate with your UI, you can create the Python engine in a background thread and set a variable in the scope to an instance of your model that your UI will query (using proper threading locks, of course). For example, I've created a harness to run PyGame games in the browser using Silverlight+IronPython+GameLight.

Welcome to the world of Python-based Rich Internet Applications!