22
Fri, Nov
1 New Articles

IronPython: Old Wine in a New Bottle

Development Tools
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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!

Prerequisites

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

•                     CPython

•                     Tinypy for embedded systems programming

 

Downloading IronPython

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."

 

Installing IronPython

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:

 

011409JoydipIronPythonSetup-1.PNG

Figure 1: The IronPython Setup Wizard gets you started.

 

Click on Next and accept the license agreement, as shown in Figure 2:

 

011409JoydipIronPython-Setup-2.PNG 

Figure 2: Accept the license agreement.

 

Click on Next and select the components you would like to install.

 

011409JoydipIronPython-Setup-3.PNG

Figure 3: Select the components to install.

 

Now, click on Next. When the setup is complete, the screen in Figure 4 appears:

 

011409JoydipIronPython-Setup-4.PNG

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:

 

class MyClass(object):

def __init__(self, message='Welcome to the World of Python'):

self.message = message

def DisplayMessage(self):

print self.message

app = MyClass ()

app.DisplayMessage()

 

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:

 

011409JoydipFig1.png

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:

 

011409JoydipFig2.png

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:

 

import sys

sys.path.append("c:pythoninstalleddirectorylib")

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();

ironPythonEngine.SetStandardOutput(myStream);

ironPythonEngine.SetStandardError(myStream);

ironPythonEngine.AddToPath(AppDomain.CurrentDomain.BaseDirectory);

ironPythonEngine.Globals.Add("MyForm", this);

 

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.Show()

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:

•                     clr.AddReference

•                     clr.AddReferenceToFile

•                     clr.AddReferenceToFileAndPath

•                     clr.AddReferenceByName

•                     clr.AddReferenceByPartialName

 

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:

 

import clr

clr.AddReference("System.Xml")

from System.Xml import *

doc = XmlDocument()

doc.Load("employee.xml")

n = doc.SelectNodes("//Employees/Employee/@Code")

for x in n: print x.Value

Suggested Readings

Here is a list of references for further study on this topic:

 

http://www.codeplex.com/IronPython

http://en.wikipedia.org/wiki/IronPython

http://blogs.msdn.com/ironpython/

http://www.theserverside.net/tt/articles/showarticle.tss?id=IronPythonGuide

http://msdn.microsoft.com/en-us/magazine/cc163344.aspx

http://www.devx.com/codemag/Article/39904/1763

http://static.asp.net/asp.net/files/IronPython/IronPython-Walkthrough03.pdf

Recap

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!

Joydip Kanjilal

Joydip Kanjilal is a Principal Software Engineer in Hyderabad, India.

Read my blog

Awarded the prestigious Microsoft Most Valuable Professional (MVP) award in ASP.NET six times in a row from the year 2007 to 2012. A speaker and author of several books and articles with over 18 years of industry experience in IT and more than 14 years in Microsoft .NET and its related technologies.

Currently working as a Principal Software Engineer at DELL International Services at Hyderabad. Was selected as an MSDN Featured Developer of the Fortnight (MSDN) a number of times and also Community Credit Winner at www.community-credit.com several times.

Authored the following books:

·  Entity Framework Tutorial (Second Edition) by Packt Publishing

·  ASP.NET Web API: Build RESTful Web Applications and Services on the .NET Framework by Packt Publishing

·  Visual Studio 2010 and .NET 4 Six-in-One by Wrox Publishers

·  ASP.NET 4.0 Programming by McGraw Hill Publishing

·  Entity Framework Tutorial by Packt Publishing

·  Pro Sync Framework by APRESS

·  Sams Teach Yourself ASP.NET AJAX in 24 Hours by Sams Publishing

·  ASP.NET Data Presentation Controls Essentials by Packt Publishing

Also reviewed more than 10 books and authored more than 350 articles for some of the most reputable sites, such as www.msdn.microsoft.com, www.code-magazine.com, www.asptoday.com, www.devx.com, www.ddj.com, www.aspalliance.com, www.aspnetpro.com, www.sql-server-performance.com, www.sswug.com, and so on.

Has years of experience in designing and architecting solutions for various domains. His technical strengths include C, C++, VC++, Java, C#, Microsoft .NET, AJAX, WCF, JQuery, ASP.NET Web API, REST, SOA, Design Patterns, SQL Server, Operating Systems, and Computer Architecture. Has been exploring Cloud technologies, IoT and Machine learning these days.

Blog: http://www.infoworld.com/blog/microsoft-coder

Website: www.joydipkanjilal.com

Twitter: https://twitter.com/joydipkanjilal

Facebook: https://www.facebook.com/joydipkanjilal

LinkedIn: http://in.linkedin.com/in/joydipkanjilal

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: