How to run IronPython code from C#

I’ve just got back from a joint session with Shay at the local .NET user group, I’ve presented IronPython after an excellent IronRuby session done by Shay.

One example I didn’t have the time to show was how to run IronPython script from within C# code. After the session I was asked by a group member to show this exact demo. So without further ado here is how to run IronPython from within the comfort of your C# application:

Step 1: Add references

Add the following assemblies to your project:

  • IronPython.dll
  • IronPython.Modules.dll
  • Microsoft.Scripting.dll

All of the assemblies above are can be found under the IronPython installation folder.

Step 2: write code

Running IronPython is very easy – I’ve decided to create a console application and run an IronPython file that was passed as an argument:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace IronPythonFileRunner
{
class Program
{
static void Main(string[] args)
{
ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
ScriptRuntime runtime = new ScriptRuntime(setup);
ScriptEngine engine = Python.GetEngine(runtime);

ScriptSource source = engine.CreateScriptSourceFromFile(args[0]);
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
}
}
}

You can use the same code to embed IronPython by replacing engine.CreateScriptSourceFromFile with engine.CreateScriptSourceFromString.

Introduction to IronPython

Want to learn more about IronPython? take a look the the whole presentation

or read my Getting Started with IronPython posts.

2 thoughts on “How to run IronPython code from C#”

  1. A really helpful post. Been looking for this all over the net. I am designing a desktop application in Visual Studio 2010, and I have some python scripts (.pyc files) which I need to call from the c# code. Well I am sort of a newcomer to this field, and as a result completely lost. I got a question though, and I guess its pretty stupid too. Where exactly do I specify the filename of the .pyc files and how? I would indeed be extremely thankful for any sort of help on the matter.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s