DLR and Iron Python

Posted: September 7, 2010 in Dotnet basics

 

DLR stands for Dynamic Language Runtime. Dotnet 4.0 supports dynamic language interaction along with static languages for which CLR extends support. Currently supported languages are Ruby and Python. The Dynamic Language Runtime enables language developers to more easily create dynamic languages for the .NET platform. In addition to being a pluggable back-end for dynamic language compilers, the DLR provides language interop for dynamic operations on objects. The DLR has common hosting APIs for using dynamic languages as libraries or for scripting in your .NET applications.

IronPython is an implementation of the Python programming language targeting the .NET Framework and Mono ( A cross platform open source Dotnet framework currently targeted for Linux). IronPython is written entirely in C#. Python is implemented on top of the Dynamic Language Runtime (DLR), a library running on top of the Common Language Infrastructure that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages. Python is mainly used by system administrators for executing scripts who do not have knowledge about .Net. Dotnet has extended support for IronPython in order to resolve this dependency so that programmers and administrators can work in conjunction.

The first step to getting started is to actual download IronPython. The project is hosted on CodePlex with all of the source code available. After the IronPython installation, its interpreter and its libraries will be installed in your Program Files directory. The interpreter is installed in ipy.exe, where ipy is pronounced “Eye-Pie.” The interpreter remains dormant when you call Python from C#. Dotnet projects which want to use Python need to reference dlls.

Sample usage of Python from IronPython console

>>> import System
>>> from System.Collections import *
>>> h = Hashtable()
>>> h["a"] = "IronPython"
>>> h["b"] = "Tutorial"
>>> for e in h: print e.Key, ":", e.Value

Once you install Iron Python, there will be Visual Studio templates available for creating the projects. Creating a sample standalone file is the best option. Create some simple script file as seen below:

File Name : Test.py

def Simple():
print "Hello from Python"
print "Call Dir(): "
print dir()

File Name : pyt.py

def factorial(n):
"factorial(n) -> returns factorial of n"
if n <= 1: return 1
return n * factorial(n-1)

Place these files in your project folder and set "Build Action" to "Content" and "Copy To Output Directory" to "Copy Always".

Now, create another application which will act as the hosting environment. Reference dlls from Program Files \ Python folder namely IronPython.dll, IronPython.Modules.dll, Microsoft.Dynamic.dll, Microsoft. Scripting.dll and Microsoft. Scripting.Debugger.dll .
Now that you have your project set up correctly you need to do two things:

1. Write or find a script containing Python code that you want to run
2. Write C# code to call the script.

Listing 2 shows a very simple IronPython script that contains a single method called Simple() that writes a few strings to a console window. Save this script to a file called Test.py, and add it to your project, as shown in Figure 2. There are several ways to do this. One is to right click on your project in the Solution Explorer, and choose Add | New Item. Add a text file, and call it Test.py. Click on the new node when it is added to your project, and set its Copy to Output Directory property to Copy Always.
Your class file from where you call the Python script will be as seen below.

Note:: The below code didn’t work along with IronPython 2.7. So, i had to setup 2.6 version and then it worked fine.

There are two examples – the first just calls one method from Python script and the second calls method, passes a parameter and captures the return value.

using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using System.IO;

namespace PythonHost
{
class Program
{
static void Main(string[] args)
{
//// Creates the python runtime
ScriptRuntime ipy = Python.CreateRuntime();

//// The dynamic keyword is needed
//// here because Python is an interpreted
//// scripting language where calls are bound
//// at run time, not at compile time.
//// There is no simple or practical way to
//// bind calls to Python at compile time
//// because Python is designed to be a
//// dynamic language which is resolved
//// at runtime.
dynamic test1 = ipy.UseFile("Test.py");

// Call function
test1.Simple();

// Sample for passing parameters to Python and getting value
dynamic test2 = ipy.UseFile("pyt.py");
int p = test2.factorial(5);
}
}
}

If all is well…you should be able to run your application.

Also, using 2.7 version I was able to setup SilverLight runtime in conjunction with Python.

I setup Silverlight class library and copied the same two scripts and added the following code to setup the execution.

using System.Windows.Controls;
using Silverlight = Microsoft.Scripting.Silverlight;

namespace SilverlightApplication5
{
public partial class MainPage : UserControl
{
public MainPage() {
InitializeComponent();

var runtime = Silverlight.DynamicEngine.CreateRuntime();
var python = runtime.GetEngine("python");
dynamic script = runtime.UseFile("pyt.py");
int p = script.factorial(5);

script = runtime.UseFile("Test.py");
script.Simple();
}
}
}

For Sliverlight with 2.7 version of IronPython, i didn’t face any issues….

Advertisements

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