Understanding Environment variables
Environment variables are simply a kind of storage location managed by the operating system. When you open a command prompt, you can see a list of environment variables by typing Set and pressing Enter. Figure 10-6 shows the environment variables on my system. The environment variables or at least their values will differ on your machine, so you should take a look at them. If you want to see the value of a particular environment variable, type Set VariableName such as Set USERNAME and press...
using Early Binding
As previously mentioned, using early binding means creating a reference to the COM component and then using that reference to interact with the component. IronPython doesn't support the standard methods of early binding that you might have used in other languages. What you do instead is create an interoperability DLL and then import that DLL into your application. The Defining an Interop DLL section of the chapter describes this process in considerably more detail. Early binding provides the...
LISTING Accessing data using a dictionary
download on Create the dictionary. Wrox.cnm PeopleColors 'George' 'Red', 'Ann' 'Purple', 'Sam' 'Yellow' print 'The color George likes best is', PeopleColors 'George' Add a new person and color. PeopleColors 'Nancy' 'Blue' Verify that the new person was added. if PeopleColors.has_key 'Nancy' print 'Added Nancy with color', PeopleColors 'Nancy' Iterate through all of the values, print ' nHere are the colors people like ' for Key, Value in PeopleColors.iteritems Pause after the debug session....
Using the Event Log
Many applications rely on the event log as a means to output data to the administrator. Of all of the methods that Microsoft has created for outputting error and status information, the event log has been around the longest and is the most successful. Fortunately, for the IronPython developer, using the event log is extremely easy and it's the method that you should use most often. Listing 10-11 shows just how easy it is to write an event log entry. listing 10-11 Writing an event log entry...
understanding the Type Library Import utility
Remember that you always use Type Library Import TLbImp for components, not for controls. Before you can use TLbImp, you need to know a bit more about it. Here's the command line syntax for the tool The TypeLibName argument is simply the filename of the COM component that you want to use to create an interop assembly. A COM component can have a number of file extensions, but the most common extensions are .DLL, .EXE, and .OCX. The TypeLibName argument can specify a resource identifier when the...
Using The Python Modules
At one point, the Python modules were stable and straightforward to use, but later versions are less stable and, when it comes to IronPython, may be missing required elements completely. Consequently, you might see tutorials such as the one at and wonder why they don't work. These tutorials are based on earlier versions of Python and don't account for the missing CPython elements in IronPython. The following sections describe how to overcome these problems in your application when you use the...
working with the collections module
Collections are another in a series of containers that you can use to store information in memory. For IronPython developers, the main reasons to use collections are IronPython doesn't include collection support by default you must import it into your application through the collections module. The collections module comes with a number of collection objects. If you're using the latest version of IronPython, you gain access to these collection features namedtuple data type factory function For...
Using IronPython with Mono
gt Defining Mono and its features Getting and configuring Mono Using Mono and IronPython together Using Mono with other .NET languages If you buy into the idea that IronPython only works on the Windows platform, you're losing out on a lot of the power of IronPython. In fact, IronPython works fine on a number of platforms, including Linux and the Macintosh. The secret, as is the case in so many situations, is to think outside the box. There's a little product called Mono that Microsoft would...
Info Gpq
TOJTKm niHHiavthi rarrwofea talw Ntuih FIGURE 2-3 Modify the properties to match your project requirements. Command line switches are case sensitive. Using the wrong case can result in unexpected behavior. For example, if you use the -s command line switch in place of the -S command line switch, you'll obtain an unexpected result from the IronPython interpreter. In this case, the interpreter won't add the user site directory to sys.path. 5. Select the Arguments field. Type -D NameOfProject,...
Info Ity
.i wj w ne Uteflici ii ft b nji liifi FIGURE 19-6 Set the Mono configuration for your project. 4. Type C Program Files IronPython 2.6 IPY.EXE -D TestMono.pyin the Arguments field change the folder location to match your IronPython installation . 5. Click the ellipses in the Working Directory field to display the Browse for Folder dialog box. Locate the folder that contains the project you're working on and click OK. The project folder appears in the Working Directory field of the Properties...
Interacting with the DLR
gt Getting your copy of the DLR Considering hosting APIs Employing extensions to the LINQ ExpressionTree Working with DynamicSite gt Understanding IDynamicObject gt Using the ActionBinder gt Considering the other DLR Features The Dynamic Language Runtime DLR is a new feature of the .NET platform. Its intended purpose is to support dynamic languages, such as Python through IronPython and Ruby through IronRuby . Without DLR, the .NET Framework can't really run dynamic languages. In addition, DLR...
Working with String objects
Strings are one of the first objects many people use. You write that first Hello World application and marvel when the words appear on screen. In fact, strings are the mainstay of many applications. Without strings you can't provide prompts to the user or ask for input. Sure, you may not do any heavy lifting with strings, but every application out there requires strings to work properly. The following sections discuss the IronPython string object in more detail. One of the problems you can...
Info Kic
FIGURE 17-14 Input boxes are good for small amounts of custom user input. method. Notice that the example code adds a call to ToString , so that the entire method call is MyForm.ShowDialog .ToString . This is a technique for converting the System.Windows .Forms.DialogResult to a simple string that you can compare with the desired output, which is 'OK' in this case. The hidden namespace provided with Visual Basic won't change names when you add the TestForm class to it. The namespace retains the...
Working with IDLE
IDLE is the IDE that IronPython should have shipped with because it lets you perform all kinds of interesting tasks using Python. To access this feature, choose Start O Programs O Python 2.6 O IDLE Python GUI . You'll see a window similar to the one shown in Figure 6-7. The window opens immediately with a fully functional interpreter by default. The interpreter is called the Shell Window. For example, in Figure 6-7, if you type 2 2 and press Enter, you'll see the answer 4 on the next line....
debugging with the python debugger
You might not know it, but Python and IronPython come with a debugger module, pdb for Python debugger . Like any module, you have full access to the debugger source code and can modify it as needed. This section describes the default debugger performance. It's possible to use pdb with any Python file by invoking the debugger at the command line using the -m command line switch. Here's how you'd invoke it for the example shown in Listing 12-1. Unfortunately, using this command line format limits...
listing An example of a Standard Library application
Available for from Tkinter import dVyiox0comn import aboutDialog Represents the main window of an application. root Tk Defines a basic test of IDLE Display the IDLE About dialog box aboutDialog.AboutDialog root, 'About' Make sure you destroy the window when you get done with it. root.destroy A very basic function in Python print 'Hello' Set the path to include the application directory. import sys sys.path.append 'C 0255 - Source Code Chapter06' print sys.path Display the IDLE About dialog box....
understanding Early and Late Binding
When you work with a class, you create an instance of the class, set the resulting object's properties, and then use methods to perform a particular task. COM lets you perform essentially the same set of steps in a process called early binding. When you work with early binding, you define how to access the COM object during design time. In order to do this, you instantiate an object based on the COM class. These sections provide an extremely simplified view of COM. You can easily become mired...
PURPOSE Idh
Provides methods for preparing Unicode strings for Internet use according to the requirements of RFC 3454 http www.faqs.org rfcs rfc3454. html . You can find out more about this module at http docs.python.org library stringprep.html. Allows a Python application to spawn subprocesses and then interact with them through their input, output, and error pipes. The host application also receives the subprocess's return code. This module replaces several older modules including os.system, os.spawn ,...
Understanding the Use of ScriptEngine
You have many options for working with IronPython scripts. This first example takes an approach that works fine for Visual Studio 2008 developers, as well as those using Visual Studio 2010. It doesn't require anything fancy and it works reliably for most scripts. Ease and flexibility concerns aside, this isn't the shortest technique for working with IronPython scripts. This is the Method1 approach to working with IronPython scripts the technique that nearly everyone can use and it appears in...
Developing the IronPython Callable Methods
The P Invoke code shown in Listing 16-5 does expose the Win32 API calls needed to perform certain tasks with IronPython. Theoretically, you could rely on just the code in Listing 16-5 to gain the access you require in IronPython. However, the task would be difficult because you'd need to work through the required bit manipulations. It's better to place the code you need to access the Win32 API in easily called methods, which is the purpose of the code in the following sections. Defining Common...
Creating the Windows Media Player Interop DLL
Now that you have an idea of how to use the AxImp utility, it's time to see the utility in action. The following command line creates an interop assembly for the Windows Media Player. This command line switch doesn't specify any options. It does include SystemRoot , which points to the Windows directory on your machine making it possible to use the command line on more than one system, even if those systems have slightly different configurations . When you execute this command line, you see the...
Working With Idynamicobject
This section discusses the IDynamicObject interface provided as part of DLR, which doesn't affect IronPython directly, but could affect how you use other languages to interact with IronPython. You can easily skip this section and leave it for later reading if you plan to work exclusively with IronPython for the time being. This is a very short discussion of the topic that is meant to fill in the information you have about DLR and its use with IronPython. As mentioned throughout the book, C and...
Notes
Provides support for the .csv file format. You can read more about this module at http pydoc .org 2.5.1 _csv.html and http docs .python.org library csv.html. Provides support for the heap queue algorithm. You can read more about this module at http pydoc.org 2.5.1 _heapq.html and http docs.python.org library heapq.html. Provides high performance logging profiler support. You can read more about this module at http pydoc.org 2.5.1 _hotshot.html and http Implements the multi-byte encoder and...
Ironpython Tutorials
FIGURE 6-1 Tell the installer whether you want a personal install or one for everyone. 3. Choose an installation location and click Next. You'll see the Customize Python 2.6.4 dialog box shown in Figure 6-2. Notice the Register Extensions entry. If you let the installer make this change, Python, not IronPython, will be the default installation. FIGURE 6-2 Customize the Python installation to meet your needs. FIGURE 6-2 Customize the Python installation to meet your needs. 4. Click the down...
Php
Developers also assign a number of advantages specifically to the Python language and IronPython's implementation of it . Whether these features truly are advantages to you depends on your perspective and experience. Many people do agree that Python provides these features Support for the Windows, Linux Unix, and Mac OS X platforms Managed support using both Java and .NET Considerable object-oriented programming OOP functionality that is easy to understand and use The capability to look within...
Using the dynamic Keyword
One of the new ways in which you can access IronPython in C 4.0 is to use the dynamic keyword. This keyword makes it possible for you to cut out a lot of the code shown in Listing 15-2 to perform tasks with IronPython. It's still not perfect, but you'll do a lot less work. Listing 15-3 shows a short example that accesses the_test__ function found in Listing 15-1. LISTING 15-3 Accessing IronPython using the dynamic keyword Available for static void Main string args download on Wrox.com Create a...
building the Full DLR
Before you can use DLR, you must build it. The previous section explains how to download a copy of the DLR source. The following sections describe three methods you can use to build DLR. For most developers, the easiest and fastest method is the command line build. However, if you want to review the code before you use it, you might want to load the solution in Visual Studio and take a peek. The command line build option requires that you use the Visual Studio command line, not a standard...
Creating the Dialog Box Library in C
Your dialog box library can support dialog boxes at two levels. It's possible to meet some IronPython needs using a simple message box or prompt box. Because these solutions are already programmed for you, supporting them through the static language, where the features are easily accessed, is a good way to save on development and debugging time. You can customize the implementation of these standardized features to make them easy to use within IronPython reducing the need to import a lot of...
performing late binding using activatorcreateinstance
The Activator.CreateInstance method is one of the more powerful ways to work with objects of all kinds. In fact, this particular method can give your IronPython applications the same kind of support as the Windows scripting engines CScript and WScript. When working with the Activator.CreateInstance method, you describe the type of object you want to create. The object can be anything. In fact, if you look through the HKEY_CLASSES_ ROOT hive of the registry, you'll find a number of objects to...
Debugging IronPython Applications
gt Diagnosing and understanding IronPython warnings Getting error information using sys Using the Python debugger to debug an application gt Using the CLR debugger to debug an application gt Using Visual Studio to debug an application Adding exceptions to your application Most applications have a bug or two in them at some point. In fact, unless your application is mind-numbingly simple making it of dubious value , you can probably count on seeing at least a few bugs. When working with a...
Importing an Assembly into the global Namespace
Sometimes you need to have an entire assembly available at a global level. Using variables to bring part of the assembly up to the right level won't work. In this case, you rely on a different import strategy than used in the section Performing a Standard Import earlier in this chapter. You've already seen this technique before as applied to Python modules, but now you'll see how it applies to .NET assemblies. Simply use the from AssemblyName import Assembly format used for Python modules. For...
S 1
IronPython 2 lt 2. amp .10920.8 gt on .NET 2.0.S0727.3fc83 y gt e help, copyright, credits or license for more information. gt gt gt import sys gt gt gt sys path.appendCC Program Files lronPython 2 .ft Tutorial' gt gt gt gt print sys.uath rC M ocuments nd Sefefrings Jolin' . ' C Pythi n2 . NL,ih' , 'C Program Fiieswlr onPython 2.6 iib', 'C Program FiiesWIronFython 2 . V LiiS' , ' C WFrograrc File s IronPython 2.fj' , 'C SProgram FilesV-IronPython 2.6 libN site packages', JC --'Program Files...
Info Qzl
There's a way around the issue of enumerated values in .NET calls. You can simply choose to create your own enumeration. For example, let's say you want to overcome the problem of working with the MessageBoxButtons enumeration. In this case, you create an enumeration and a new override of the ShowMessage method as shown here. public String ShowMessage String Msg, String Title, ButtonTypes Buttons Notice that you must still use coercion to make the MessageBox.Show call. However, the IronPython...
Writing an IronPython Application to Use PInvoke
If you've been following along with the example, you know it's finally time to use the ConMode class with IronPython. It's now possible to determine the display mode, the size of the console window, and the capabilities it provides. Listing 16-9 shows the code used for testing this extension. LISTING 16-9 Testing the Win32 API extension Import the Common Language Runtime. import clr Access the extension. clr.AddReferenceToFile 'Win32API.DLL' import Win32API LISTING 16-9 continued TestWin32...
Considering a Few Things IronPython Cant Test
Earlier, you learned that IronPython tests application elements using a black box approach given a particular input, what should the element provide as output However, there are other limitations you need to consider in the way IronPython performs testing. For example, IronPython can't perform stress testing. If you want to test your application in a memory-starved environment, then you need to combine IronPython with another tool. For example, you might want to read the article at http...
LISTING Testing the event class
Set up the path to the .NET Framework, import sys Add any required references. Import the .NET assemblies. import System import the NewEventClass. from NewEventClass import Create the event handler. def HandleMsg Msg Define the event and add the handler to it. ThisEvent MyEvent ThisEvent.Add HandleMsg Define the event handlers, def btnFireEvent_Click args Fire the event. ThisEvent.Fire 'Hello World' Close the application. TestForm.Close Define the Windows Form and the elements of this specific...
An overview of the Mono Family
You can obtain Mono for a considerable number of platforms. In fact, the makers of Mono add new platforms with every release. At one time, Mono worked on just a few Linux implementations, Windows, and the Mac OS X. Over time, Mono support has increased to the exciting list of platforms that follows. LiveCD This is actually an openSUSE 11.2.1 http www.opensuse.org en LiveCD a CD or DVD that contains a bootable image see http en.wikipedia.org wiki Live_CD for details that includes Mono 2.6.1. Mac...
Exploring the Windows Media Player Interop DLL
When working with imported Python modules, you use the dir function to see what those modules contain. In fact, you often use dir when working with .NET assemblies as well, even though you have the MSDN documentation at hand. Theoretically, you can also use dir when working with imported COM components as well, but things turn quite messy when you do. The Using the Windows Media Player Interop DLL section of this chapter describes how to import and use an interop assembly, but for now, let's...
Defining the IronPython Class
An IronPython class can have both attributes properties and methods, just as any class in any other language can have. However, IronPython classes have a few quirks as well. Listing 5-1 shows an example of a simple IronPython class. You've probably worked with a language that has both structures and classes. The structures serve as a means to tightly pack information and possibly add some information to it. Using structures in other languages usually incurs a performance benefit at a cost of...
Working with xmldomminidom
The xml.dom.minidom module is designed to help you work with XML using the DOM approach. However, this module is far from complete in IronPython, partly due to the CPython support required in standard Python. The actual document support is complete, so you won't have a problem building, editing, and managing XML documents. It's the write and read support that are lacking. Fortunately, you can overcome write issues by using a different approach to outputting the document to disk or other media ....
Creating a Decision Tree Using if elif else
Many programming languages provide a special structure to handle complex decisions. IronPython keeps things simple by relying on a special form of the if statement, the if elif else statement. As you might expect, each elif clause includes a Boolean expression. In many respects, the elif clauses act as the case clauses for the Select Case structure. Of course, you gain some flexibility because the elif clause need not match a particular variable. The else clause acts like the default clause for...
Defining An Interop Dll
Before you can do much with COM, you need to provide some means for .NET managed code and the component native code to talk. The wrapper code that marshals data from one environment to another, and that translates calls from one language to the other, is an interoperability interop assembly, which always appears as a DLL. Fortunately, you don't have to write this code by hand because the task is somewhat mundane. Microsoft was able to automate the process required to create an interop DLL. Of...
understanding the ActiveX Import utility
The example in this chapter relies on the ActiveX Import AxImp utility because it produces the files you need to create a control with a visual interface rather than a component. When you use this utility, you obtain two files as output. The first contains the same information you receive when using the TLbImp utility. The second, the one with the Ax prefix, contains the code for a control. Before you can use AxImp, you need to know a bit more about it. Here's the command line syntax for the...
Creating An Ironpython Application With Mono
It's time to begin working with Mono and IronPython to create an application. Of course, you'll want to know a bit more about how Mono works before you just plunge into the project, so the first step is to look at Mono from a command line perspective. The first section that follows shows how to create an IPY environment variable and use it to open the IronPython console using Mono whenever you need it. The sections that follow show how to create a project, build a simple IronPython application,...
index 1
' lt ', string formatting, 84 ' ', string formatting, 86 ' ', string formatting, 85 '-', string formatting, 85 ' ', string formatting, 84 Click, 148 event handler, 148 - , event handler, 148 AxImp, 171 TLbImp, 170 , escape code, 34 -3, command line switch, 17 lt gt angled brackets , calling syntax, 204 asterisk , global namespace, 121 colon dictionaries, 75 if, 49 curly brackets , dictionaries, 75 - dash ILDasm, 174 options, 198 command line, 219 slash , 276 arguments, 198 command line, 219...
Creating the User Interface Library Module
From an IronPython perspective, user interface elements come in two forms messages boxes and Windows Forms. Obviously, Visual Basic.NET can create a host of user interface presentations, but if you start at this basic level, you'll find the task of creating a user interface library module easier. The following sections describe how to create both a message box class and a Windows Forms class that you place in a single DLL for use with your IronPython application. Of course, a production DLL...
using Late Binding
When using late binding, you create a connection to the COM component at run time by creating a new object or reusing a running object. Some developers prefer this kind of access because it's less error prone than early binding where you might not know about runtime issues during design time. Here are some other reasons that you might use late binding. More connectivity options You can use late binding to create a connection to a new instance of a COM component see the Performing Late Binding...
understanding the Elements of a Window
Before you tackle an IronPython Windows Forms application, it's a good idea to spend a little time looking at simple examples in languages you know. If you don't have a simple example to review, check out CSharpExample, which is provided with the book's source code. The frmMain .Designer.CS file is the best place to start. p'T flu'i Wuidinn FjrTp Dcilgurr ijriLcriLEd Ludr HI AF ulrpd hp LInid hm- flf. aj rin i- lt .11 i wi'-l - i amp i III eSitlrtfci r till bp Mind -jlll lh l ctiEf m 1 1 ryi...
Using the XMLUtil Module to View XML Data
As previously mentioned, the XMLUtil.py file isn't anything so advanced that you couldn't put it together yourself, but it's an interesting module to work with and use. Listing 13-2 shows a short example of how you could use this module in an application. listing 13-2 Walking an XML document using XMLUtil Available for Add the path required to import xmlutil. download on import sys Wrox.com import sys sys.path.append 'C Program Files IronPython 2.6 Tutorial' Import xmlutil to access the Walk...
Using the traceback Module
The traceback module adds to the capabilities of the sys module described in the Using the sys Module section of the chapter. In addition, it adds to the standard exception handling capabilities of IronPython by making it easier to obtain complex information about exceptions in general. The traceback module does focus on tracebacks, which are the IronPython equivalent of a call stack. The most common call is traceback.print_exc . Essentially, this call prints out the current exception...




