Thursday, August 19, 2010

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.
Read more: Helper Code