|
|
||||||||||||||||||
|
|
||||||||||||||||||
![]() |
![]() |
Issue 7 - Revision 6 / February 27, 2005
|
|||
|
Python on .NET - - - - - - - - - - - - By Brian Quinlan | October 22, 2004 Introduction Microsoft Corporation’s.NET generally provokes strong reactions from software developers.
Some developers shun .NET, discounting it as a poor reimplementation of Java or just another way for Microsoft to lock-in developers to its platform. Other programmers embrace .NET as a vast improvement — a way to (finally) drag Windows developers away from C++ and the Microsoft Foundation Classes to a higher-level development model. And yet other coders just scratch their heads, confused about the scope, features, and benefits of .NET. Indeed, thanks to Microsoft marketing efforts, “.NET” is the most overloaded “brand” in the entire computer industry. But apathy or confusion shouldn’t cause Python developers to disregard .NET. In fact, in the true spirit of Python, .NET allows Python developers to integrate Python with a great deal of valuable Windows software, including key technologies such as XML, SOAP, ADO, and the Windows graphical user interface (GUI). While writing extensive Windows application with Python and .NET is still in the realm of science fiction, recent, important advances have made simple applications quite doable. Let’s take a look at .NET, specifically the .NET Framework, and see how to write Python applications with it. The .NET FrameworkThe .NET Framework (often referred to as “.NET”, albeit confusingly) is Microsoft’s implementation and extension of the ECMA-335: Common Language Infrastructure (CLI) standard. According to ECMA-335, “the CLI allows applications written in multiple high level languages to be executed in different system environments without the need to rewrite the application to take into consideration the unique characteristics of those environments.” The .NET Framework consists of two main components: the Common Language Runtime (CLR) and the .NET Framework class library. The Common Language Runtime is the infrastructure that allows applications to access the .NET Framework class library. Similar to Java’s or Python’s virtual machine, the CLR provides common data types (integers, floating-point numbers, strings, and so on), and a virtual machine that executes Intermediate Language (IL) assembly language. IL is similar to Python byte code, but as with the rest of .NET, was designed to be programming language independent. For example, because of IL programmers can now mix Visual Basic, Visual C++, and a new (Java-like) language called C# (pronounced “C-Sharp”). The .NET Framework class library (usually just called the “.NET Framework”) provides a wide variety of features in an object-oriented programming library. Like Python and Java, the .NET Framework organizes code into related, hierarchical groups called “namespaces.” All of the classes in the .NET class library are in one of two top-level namespaces: System or Microsoft. The System namespace contains the most features and is (largely) platform independent. It draws graphics and creates user interfaces, and contains code that defines and manipulates data structures, event handlers, exceptions, and more. For instance, System.Collection contains classes that can be used to store other objects. Some of these classes have direct Python equivalents, such as ArrayList (list), Queue, and Hashtable (dictionary). Others, like Systems’ SortedList (really an ordered dictionary), are unique. The System.Data namespace contains classes to manipulate data from OLE databases and from XML files, and System.Diagnostics namespace provides classes for logging, debugging, creating and querying performance counters and for retrieving information on processes. The Microsoft namespace contains classes related to Microsoft-specific technologies, such as the Windows registry, Windows-specific events, and application scriptability. Let's Get CodingLet’s take a break from theory and start coding. To follow along you must first install the .NET Framework and some tools for accessing it from Python. The .NET Framework is available for Windows, Linux, and Mac OS X. Microsoft distributes the most complete .NET implementation for Windows. Microsoft’s code is available either through Windows update or at http://msdn.microsoft.com/netframework/downloads/framework1_1/. Meanwhile, the Mono project provides a .NET implementation for Linux, Mac OS X, and Windows. It can be downloaded from http://www.mono-project.com/downloads/. Once you’ve installed a version of the .NET Framework on your computer, you’ll still need some way of accessing the .NET Framework class libraries from Python. There are currently two tools for mixing .NET and Python: Python for .NET and IronPython. Python for .NET is implemented as a Python extension module that allows CPython scripts to access the .NET Framework. It’s available from http://www.zope.org/Members/Brian/PythonNet/index_html. The advantage of Python for .NET is that it allows you to continue to use existing Python libraries and extensions while simultaneously taking advantage of the .NET Framework class libraries. Its disadvantage is that is that there is no convenient way to make services available to CLR applications. For example, writing a class that can be directly instantiated by other CLR languages is not possible. IronPython is written in C# and compiles Python source code to IL assembly, just as Jython is written in Java and compiles Python source code to Java bytecode. (The similarity of the two approaches is not surprising considering that Jim Hugunin is the author of both.) In addition to the ability to compile standalone applications, IronPython also provides a shell for interactive use. IronPython can be found at http://ironpython.com. IronPython’s primary advantages and disadvantages are the opposite of Python for .NET’s: existing Python C extensions are not available from IronPython. In fact, since most Python modules are layered upon C extensions at some level, and only the math have sys modules have been reimplemented in C#, very few existing Python modules can be used. However, the advantages of this approach is that it should eventually be possible to make Python classes available to other CLR languages, and IronPython scripts should be executable without the need to install CPython. Another interesting aspect of IronPython is that it has already been demonstrated to run nearly as fast as CPython, and Jim Hugunin suspects that IronPython can be made faster than CPython without a Herculean effort. At First GlanceKeeping with tradition, the first example, which immediately follows, displays a form containing the text “Hello World”. It can be run using either Python for .NET or IronPython.
One important feature demonstrated in this example is the “Dock” property. The “Dock” property is common to all controls in the .NET Framework class library and, when combined with the “Anchor” property, is used to position controls insides window. In this example the “Dock” property is set to cause the contents of the control to fill the entire window. Hwever, it can also be used to position a status bar at the bottom of a window or to keep a button centered. By using various settings of the “Dock” and “Anchor” properties, complex control layouts can be achieved. For instance, a list box can expand vertically when a window is resized, but otherwise maintains the same top and horizontal positions. Delegates and EventsIf you consider the previous example, it’s missing something common to nearly all GUI applications: it doesn’t respond to user input. In the .NET Framework class library, when the user takes an action, such as clicking the mouse or typing on the keyboard, a method or function is called to respond to it.
This approach is somewhat unique among statically-typed object-oriented environments and is possible because, unlike other similar systems, such as C++ and Java, the .NET Framework allows methods to be passed and used between objects. Methods used in this fashion are wrapped in type-safe objects called delegates. One nice aspect of writing in Python is that both IronPython and Python for .NET automatically create delegates from functions and methods for you, so no explicit wrapping is required. Since delegates are actual objects, they can be subclassed to offer more sophisticated behavior. The most commonly used delegate subclass is called MulticastDelegate. This class allows many functions or methods to be triggered by a single event. Multicast delegates make it easy to implement powerful observer-style patterns. In a GUI application, for example, many different components may be interested in knowing when the application is shutting down so windows can be closed, network resources freed, and files saved. In the .NET Framework, when delegates are used to handle events, they are always passed two arguments.
In the following example, two delegate functions are added (using the “+=” or in-place addition syntax) to monitor changes in the value of a track bar control. One function modifies the transparency of a window, while the other displays the value of the track bar in the status bar at the bottom of the window. A screen capture of the application, obscuring a Notepad window, appears below.
A Bigger example The final example ties in a lot of the ideas presented above and adds a few extra twists. This example application shows an empty window area with a tracker control and a status bar at the bottom. When the empty portion of window is left-clicked, a point is drawn at that location. When two or more points have been created, they are joined by a curved line. The amount that the line curves is controlled by the tracker control. In addition, if the window is right-clicked, a contextual menu appears giving you the ability to clear the curve drawing or save it as a GIF image. As part of the save progress, you’re shown a standard save dialog box prompting for the name of the file. When the application window is closed, you’re prompted to save your image unless you have already done so and not made any changes since then. The application demonstrates handling several different event types, creating a contextual menu, and creating a Panel control to draw in. This example can only be run using Python for .NET because IronPython does not yet support several required delegate types.
Conclusion Before you set out to build your own .NET applications using Python, keep in mind that the limitations of the current tools preclude writing sophisticated applications. Instead, the current tools provide a glimpse into the possibilities that the .NET Framework can provide for Python developers: robust cross-language functionality and best-of-breed applications for Microsoft operating systems. So download Python for .NET and IronPython, read-up on the .NET Framework class libraries, and keep an eye out for future developments.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Py is committed to bringing you great Python Articles. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
Reproduction of material from any of PyZine's pages without prior written permission is strictly prohibited. Copyright 2003 - 2005 PyZine |
|