My Life As A Blog

Running Python from C#

with one comment

Having posted a number of times about Ruby over the last few months, I thought I should also write a bit about Python.  The first thing I decided to try and do was to run some IronPython from C#.  I downloaded version 2.0 beta 5, which includes the latest version of the DLR.  I created a Console Application and added references to Microsoft.Scripting.dll and Microsoft.Scripting.Core.dll – the assemblies that constitute the DLR.  I also added a reference to IronPython.dll and IronPython.Modules.dll.  I decided to try to output some text, set a variable in IronPython and retrieve the value in C#.  Here’s the code:

ScriptRuntimeSetup setup = new ScriptRuntimeSetup();
ScriptRuntime runtime = new ScriptRuntime(setup);
ScriptEngine engine = runtime.GetEngine("IronPython");
ScriptScope scope = engine.CreateScope();
ScriptSource source = engine.CreateScriptSourceFromString("print 'Hello World'\r\na=1", SourceCodeKind.Statements);

I’m impressed that C# and IronPython can interact like this.  The possibilities for extending applications with runtime dynamic code are intriguing  – worth looking into.

Written by remark

September 23, 2008 at 10:04 pm

Posted in .NET, c#, Python, Software, Tools

One Response

Subscribe to comments with RSS.

  1. nice share, thanks..


    June 15, 2010 at 9:46 am

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: