Programming / Development Tools
Learn how to write simple programs in IronPython and access .NET libraries with IronPython code.
IronPython, an open-source project at CodePlex, is the latest implementation of the Python programming language in the managed environment of the Microsoft .NET framework. In IronPython, you can use all .NET libraries while writing your Python language-style code. This article examines this new offering's features and benefits. It also discusses how you can easily integrate your Python code into .NET applications and how you can call .NET libraries from your IronPython code, while still leveraging the benefits of .NET's managed platform.
Looking Back in Time
The IronPython project was started by Jim Hugunin as an implementation of the Python programming language on top of the Java Virtual Machine (JVM). Later, it was implemented on top of Microsoft's Common Language Runtime (CLR). The IronPython programming language was released as an open-source license with the name "Microsoft Public License." Version 1.0 of IronPython was released in September 2006. As of this writing, the stable version of IronPython is IronPython 2.0, targeting Python Version 3.5. The interesting thing to note here is that the IronPython programming language was written entirely using C#, though some of it was also written by Python itself!
To run Iron Python programs, you should have the following installed in your system:
• Microsoft .NET Framework Version 3.5
• Microsoft .NET Framework Version 3.0 SP1 or higher
• Visual Studio 2005 or 2008 or higher
Common Python Implementations
Here is a list of some common Python implementations:
• IronPython for Microsoft .NET CLR
• Jython for the Java Virtual Machine
• Tinypy for embedded systems programming
The CodePlex team states, "IronPython 2.0 is the culmination of nearly two years worth of work resulting in a CPython 2.5 compatible release on .NET 2.0 SP1. By far, the biggest change to 2.0 is that our 1.1 codebase was refactored to run on top of the Dynamic Language Runtime. With this we automatically get improvements in many feature areas such as better .NET interop support and hosting Python from managed code."
You can download IronPython here. To install IronPython in your system, double-click on the IronPython.msi file. The screen shown in Figure 1 appears:
Figure 1: The IronPython Setup Wizard gets you started.
Click on Next and accept the license agreement, as shown in Figure 2:
Figure 2: Accept the license agreement.
Click on Next and select the components you would like to install.
Figure 3: Select the components to install.
Now, click on Next. When the setup is complete, the screen in Figure 4 appears:
Figure 4: Setup is complete!
Now, click on Finish. You have successfully installed IronPython in your system! You are now well set to use IronPython in your applications. But, before you do that, let's quickly recap what the Microsoft .NET Framework is all about.
Introducing the Microsoft .NET Framework
Before we delve into what IronPython is and how we can use it in our applications, let's have a quick look at what the Microsoft .NET Framework is all about. The Microsoft .NET framework, introduced in the year 2000, is a platform-independent distributed computing model that promises to be the technology of choice for building robust, scalable, portable applications for a long time to come. It provides support for fast development and a simplified deployment model. The Common Language Runtime (CLR) is actually the runtime execution engine of Microsoft .NET that provides an environment to execute programs that are targeted at the .NET platform. The CLR is the core of the Microsoft .NET Framework and provides a lot of services, namely these:
• Memory management
• Code verification
• Type identification
• Exception handling
• Automatic garbage collection
• The Common Type System (CTS)
• Garbage collection
What Is IronPython, Anyway?
The Python programming language is a high-level, open-source, cross-platform, procedural, dynamically typed, interpreted language. And Python is also a multi-paradigm language. What's that? It implies that it has support for diverse styles of programming. i.e., procedural, object-oriented, functional, and even meta-programming! The Python programming language official Web site states, "Python is a dynamic object-oriented programming language that can be used for many kinds of software development. It offers strong support for integration with other languages and tools, comes with extensive standard libraries, and can be learned in a few days. Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code."
IronPython is the Microsoft .NET implementation of the Python programming language. It is a dynamic programming language. Dynamic languages are those that are dynamically typed. In essence, this implies that you need not declare the type of the variables for such languages. You can readily change the type of an object at will, too! And you can examine and edit instances at runtime. Awesome, isn't it? IronPython is the name given to the implementation of the Python programming language on top of the managed environment of the CLR. Source code written in IronPython is compiled by the IronPython Engine to produce an assembly that is in turn executed by the managed environment of the CLR.
Benefits of IronPython
The IronPython programming language is dynamically compiled and has built-in support for garbage collection like other CLR-compliant programming languages. In essence, while programming in IronPython, you can use the powerful features of the Python programming language while still leveraging the benefits of the managed environment of the CLR. Cool, huh? The advent of the IronPython programming language in the managed environment of the CLR provides a lot of benefits, namely these:
• Support for dynamic typing
• Support for procedural, functional, object-oriented programming
• Support for rapid development
• Support for embedded scripting
• Support for seamless extendibility
• Support for accessing .NET managed libraries
• Support for accessing .NET objects from IronPython script using reflection
Programming in IronPython
When you write your program in IronPython and compile it, dynamic assemblies that target the CLR are created. Assemblies are the primary building blocks of the .NET framework. code reuse code reuse code reuse An assembly can contain one or more files. An assembly that contains a single file is called a single-file assembly; an assembly that contains multiple files or .NET modules is called a multi-file assembly. Assemblies are great as they provide support for versioning, type identification, deployment, code reuse, and security of Microsoft .NET applications.
The following code snippet illustrates how you can use IronPython to display a message to the user:
def __init__(self, message='Welcome to the World of Python'):
self.message = message
app = MyClass ()
The IronPython Interactive Console
You can also write your programs using the IronPython interactive console. It is present in your IronPython installation directory as a tool called ipy.exe. When you invoke the IronPython interactive console, it looks like the screen shot below:
Figure 5: Use the Iron Python Interactive Console to write programs.
Now, when you write your code in this console, the IronPython interactive interpreter interprets it and produces the desired output (if all goes well). The following screen shot illustrates this:
Figure 6: Do your work in the Iron Python Interactive Console.
Note: To use the CPython standard libraries from your Iron Python code, you need to add the "lib" directory of CPython to the path as shown below:
You should replace the "pythoninstalleddirectory" string in the example above with the name of the directory where CPython has been installed in your system.
Integrating IronPython with .NET Applications
Note that IronPython is built on top of the Dynamic Language Runtime (DLR), which houses the Dynamic Type System (DTS) and the Dynamic Language Hosting Environment (DLHE). This seamless integration of the DLR with the CLR is one of the most significant reasons for the increasing popularity of the IronPython programming language. The MSDN states, "As a first-class .NET language, IronPython integrates simply and easily with standard .NET features. This includes subclassing classes and implementing interfaces from .NET. IronPython knows about common .NET libraries and namespaces like System, which can be imported and used in a straightforward manner."
Integrating IronPython to an existing .NET application is easy. Here are the steps that you need to follow:
• First, add a reference to the file IronPython.dll.
• Create an instance of PythonEngine.
• Now, add all the instances that you want to expose using scripting to pythonEngine.Globals.
• Finally, redirect the standard output and error streams appropriately.
The following code snippet illustrates what we just discussed:
Options.PrivateBinding = true;
PythonEngine ironPythonEngine = new PythonEngine();
MyStream myStream = new MyStream();
Note that the MyStream class is a custom class that you need to derive from the Stream class.
Accessing WPF Libraries from IronPython
Windows Presentation Foundation (formerly known as Avalon) is a framework based on XAML that promotes a consistent programming model for designing and implementing applications with a clear isolation between the user interface and the business logic layers. One of the many striking features of IronPython is its ability to program dynamically. You can import .NET libraries dynamically and use them in your code. Here is a snippet of code that illustrates how you can use IronPython to dynamically import the WPF library, create a new window instance, and set the window's title and text.
from avalon import *
w = Window()
w.Title = "My First WPF Application at Work!"
w.Content = TextBlock()
w.Content.Text = "WPF from IronPython"
Referencing .NET Libraries from Your IronPython Code
You can also add references to .NET libraries from your IronPython code. To do this, you have the following built-in functions of the clr module:
The following example illustrates how you can add a reference to the System.Xml namespace in your IronPython code, create a document instance, and then use it to query a document file:
from System.Xml import *
doc = XmlDocument()
n = doc.SelectNodes("//Employees/Employee/@Code")
for x in n: print x.Value
Here is a list of references for further study on this topic:
IronPython is the name given to the version of the Python programming language that runs on top of the Microsoft .NET Framework. Unlike the Python programming language, which is completely open source, the IronPython programming language has been released under the Microsoft Public License. This article has examined the IronPython programming language and explained how it integrates with the managed environment of the CLR. We also discussed how to write simple programs in IronPython and how to access .NET libraries from IronPython code. Happy reading!