Professional IronPython - John Paul Mueller - E-Book

Professional IronPython E-Book

John Paul Mueller

0,0
30,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Thorough coverage of Microsoft's new dynamic programminglanguage: IronPython IronPython is a powerful and vital part of any .NET developer'stoolbox, and although it is several years old, very littleliterature exists on the topic. This essential resource fills thatvoid and provides you with an in-depth understanding ofIronPython. A brief introduction walks you through the installation, usage,and tools of IronPython and also explains what makes IronPythondifferent from other programming languages. Coverage quickly moveson to explaining how to use and work with the IronPython language,and an in-depth look at its environment sheds light on how it canbe stand alone or with the .NET Framework. You'll see howIronPython can be used to create either desktop or Web-basedapplications and you'll witness how it interacts with otherexisting technologies. In addition, coverage of advanced topicsshares techniques for extending IronPython and making it a robustlanguage. * Provides you with an in-depth look at IronPython, how it isdifferent from other programming languages, what it is capable of,and how to maximize its potential * Explores how IronPython interacts with existing technologiesand how it can perform administration tasks * Answers popular questions, such as how to extend IronPython andmake it a more robust language * Tackles topics not addressed anywhere else, including executingIronPython using Mono You'll want to devour every topic covered in ProfessionalIronPython so you can get started working with this powerfulprogramming language today.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 736

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Cover

Title Page

Copyright

Dedication

About the Author

About the Technical Editor

Credits

Acknowledgments

Introduction

Who This Book Is For

What This Book Covers

How This Book Is Structured

What You Need to Use This Book

Conventions

Source Code

Errata

p2p.wrox.com

Part I: Introducing IronPython

Chapter 1: Discovering IronPython

An Overview of IronPython

Getting IronPython

Understanding the Dynamic Language Runtime

Using the IronPython Console

Using the IronPython Windowed Environment

Creating Your First Application

Using IronPython Constructively

Chapter 2: Understanding the IronPython Basics

Using Visual Studio to Create IronPython Applications

Understanding the Use of Indentation and Capitalization in IronPython

Considering Data Types in IronPython

Exploring the IronPython Modules

Interacting with the IronPython Environment

Using IronPython Constructively

Part II: Using the IronPython Language

Chapter 3: Implementing Structured Language Elements

Stringing Statements Together

Selecting Between Options

Creating Loops

Performing Enumerations

Using IronPython Constructively

Chapter 4: Using Arrays and Collections

Working with Tuples, Lists, and Arrays

Working with the collections Module

Using Dictionaries

Using IronPython Constructively

Chapter 5: Interacting with Structures and Objects

Working with Existing Objects

Creating New Objects

Using IronPython Constructively

Part III: Working with IronPython

Chapter 6: Using the Python Standard Library

Considering the Standard Library Features

Obtaining and Installing the Python Standard Library

Accessing the Standard Library from IronPython

Using the Standard Library Features

Using IronPython Constructively

Chapter 7: Accessing the .NET Framework

Importing the .NET Framework Assemblies

Using .NET Data Types

Interacting with .NET Framework Elements

Working with Generics

Using IronPython Constructively

Chapter 8: Creating Windows Forms Applications

Working without a Visual Designer

Defining Windows Forms

Interacting with Predefined and Custom Events

Using IronPython Constructively

Chapter 9: Interacting with COM Objects

An Overview of COM Access Differences with Python

Choosing a Binding Technique

Defining an Interop DLL

Performing Late Binding Using Activator.CreateInstance()

Performing Late Binding Using Marshal.GetActiveObject()

Using IronPython Constructively

Chapter 10: Using IronPython for Administration Tasks

Understanding the Command Line

Interacting with the Environment

Starting Other Command Line Applications

Providing Status Information

Using IronPython Constructively

Chapter 11: Developing ASP.NET Applications

Considering IronPython Web Application Compatibility

Obtaining ASP.NET Dynamic Language Support

Creating a Web Site

Building a Basic ASP.NET Site Using IronPython

Using IronPython Constructively

Chapter 12: Debugging IronPython Applications

Understanding IronPython Warnings

Obtaining Error Information

Debugging with the Python Debugger

Debugging with the CLR Debugger

Using Visual Studio for IronPython Debugging

Defining and Using Exceptions

Using IronPython Constructively

Part IV: Advanced IronPython Topics

Chapter 13: Working with XML Data

Using the .NET XML Functionality

Using XMLUtil

Using the Python Modules

Using IronPython Constructively

Chapter 14: Interacting with the DLR

Obtaining DLR

Working with Hosting APIs

Understanding the Extensions to LINQ Expression Tree

Considering DynamicSite

Working with IDynamicObject

Understanding the ActionBinder

Understanding the Other DLR Features

Using IronPython Constructively

Chapter 15: Using IronPython from Other .NET Languages

Understanding the Relationship Between Dynamic and Static Languages

Creating an Externally Accessible IronPython Module

Accessing the Module from C#

Accessing the Module from Visual Basic.NET

Developing Test Procedures for External Modules

Debugging the External Module

Using IronPython Constructively

Chapter 16: Extending IronPython Using C#

Understanding the Requirements for an Extension

Considering IronPython and Static Language Differences

Creating the Simple C# Extension

Using C# for User Interface Support

Using C# for Win32 Support

Using IronPython Constructively

Chapter 17: Extending IronPython Using Visual Basic.NET

Considering C# and VISUAL BASIC.NET Extension Similarities

Creating the Simple Visual Basic.NET Extension

Using Visual Basic.NET for User Interface Support

Using Visual Basic.NET for Database Support

Using IronPython Constructively

Chapter 18: Using IronPython for Application Testing

Understanding Why You Want to Use IronPython for Testing

Considering the Test Environment

Testing DLLs

Testing Applications

Performing Command Line Tests

Using IronPython Constructively

Chapter 19: Using IronPython with Mono

What Is Mono?

Obtaining and Installing Mono

Creating an IronPython Application with Mono

Interacting with Other .NET Languages Under Mono

Using IronPython Constructively

Appendix A

Implementing Standard Types, Functions, and Behaviors

Missing CPython Libraries

Missing or Changed Extension Modules

Using Custom CPython Extensions

Interacting with the Interpreter and Environment

Using Garbage Collection

Appendix B

Obtaining the Extensions

Overcoming Potential Extension Problems

Obtaining Third-Party Solutions

Index

Advertisement

Professional IronPython™

Published by

Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256www.wiley.com

Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-54859-2

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at .

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

Library of Congress Control Number: 2010921245

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. IronPython is a trademark of Python Software Foundation Corporation. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.

This book is dedicated to my beautiful wife, Rebecca, my inspiration and joy. She believed in me when all others doubted.

About the Author

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 84 books and more than 300 articles to date. The topics range from networking to artificial intelligence and from database management to heads-down programming. Topics for some of his current books include Windows power optimization, Windows Server 2008 GUI, and Windows Server 2008 Server Core, and he has also written a programmer’s guide that discusses the new Office Fluent User Interface (RibbonX). His technical editing skills have helped more than 63 authors refine the content of their manuscripts. John has provided technical editing services to both DataBased Advisor and Coast Compute magazines. He’s also contributed articles to the following magazines: CIO.com, DevSource, InformIT, Informant, DevX, SQL Server Professional, Visual C++ Developer, Hard Core Visual Basic, asp.netPRO, Software Test and Performance, and Visual Basic Developer.

When John isn’t working at the computer, he enjoys spending time in his workshop crafting wood projects or making candles. On any given afternoon, you can find him working at a lathe or putting the finishing touches on a bookcase. He also likes making glycerin soap, which comes in handy for gift baskets. You can reach John on the Internet at [email protected]. He is also setting up a Web site and blog at http://www.johnmuellerbooks.com/; feel free to look and make suggestions on how he can improve it.

About the Technical Editor

Russ Mullen has been consulting and programming for more years than he cares to remember. He has tech edited more than 70 books, ghost-written chapters, and co-authored several books.

Credits

Acquisitions Editor

Paul Reese

Project Editor

William Bridges

Technical Editor

Russ Mullen

Production Editor

Kathleen Wisor

Copy Editor

Nancy Rapoport

Editorial Director

Robyn B. Siesky

Editorial Manager

Mary Beth Wakefield

Associate Director of Marketing

David Mayhew

Production Manager

Tim Tate

Vice President and Executive Group Publisher

Richard Swadley

Vice President and Executive Publisher

Barry Pruett

Associate Publisher

Jim Minatel

Project Coordinator, Cover

Lynsey Stanford

Compositor

Craig Woods, Happenstance Type-O-Rama

Proofreader

Nancy Carrasco

Indexer

Robert Swanson

Cover Designer

Michael E. Trent

Cover Image

© Ameng Wu/stockphoto

Acknowledgments

Thanks to my wife, Rebecca, for working with me to get this book completed. I really don’t know what I would have done without her help in researching and compiling some of the information that appears in this book. She also did a fine job of proofreading most of my rough draft.

Russ Mullen deserves thanks for his technical edit of this book. Russ added greatly to the accuracy and depth of the material that you see here. I appreciated the time that Russ devoted to checking my text, especially the code, for accuracy. As I wrote this book, I also spent a good deal of time bouncing ideas off Russ, which is a valuable aid to any author.

Matt Wagner, my agent, deserves credit for helping me get the contract in the first place and taking care of all the details that most authors don’t consider. I always appreciate his assistance. It’s good to know that someone wants to help.

A number of people read all or part of this book to help me refine the approach, test the examples, and generally provide input that all readers wish they could have. These unpaid volunteers helped in ways too numerous to mention here. I especially appreciate the efforts of Eva Beattie, Osvaldo Téllez Almirall, and all the others who provided input on this book. I’d like to thank each person by name who wrote me with an idea, but there are simply too many.

Finally, I would like to thank William Bridges, Nancy Rapoport, Kathleen Wisor, and the rest of the editorial and production staff for their assistance in bringing this book to print. It’s always nice to work with such a great group of professionals.

Introduction

IronPython is probably going to be one of the most interesting and flexible languages you’ve ever encountered. If you’ve never tried a dynamic language, you’re really missing something. Dynamic languages make it easy for you to try things on-the-fly, and IronPython is king when it comes to melding the flexibility of both the Python programming language and the functionality of the .NET Framework. You get an amazing array of application development tools with few hindrances to sour the experience. Professional IronPython provides you with a guided tour of this amazing language and makes it possible for you to get started writing applications quickly.

The emphasis of IronPython is fast. You write less code and the code that you do write is easier to understand, making development fast. In the past, using an interpreter meant sluggish application performance, but IronPython is anything but sluggish. Applications you develop using IronPython run quickly because they don’t include all of the cumbersome baggage that static languages such as C# and Visual Basic.NET include. Professional IronPython helps you understand the benefits of using IronPython and demonstrates techniques to obtain what you want with little fuss and considerable speed.

One of the most amazing parts of IronPython is that it’s incredibly easy to add whatever you need to it. IronPython is designed to provide extensive modularity so that you can create extensions to the basic language as dictated by your development needs. Professional IronPython shows you how to create extensions for IronPython that fill in all the gaps you might find.

Do you need multi-platform support for your project? Amazingly, IronPython can provide multi-platform development, despite what you might have heard online. Professional IronPython devotes an entire chapter to the topic of getting your IronPython application onto other platforms such as Linux and the Mac OS X.

Obviously, nothing is perfect. IronPython does have a few blemishes and you’ll want to know about them. Professional IronPython doesn’t whitewash the problems and try to dress them up as features. This book tackles the issues you’ll encounter head on and makes it a lot easier for you to overcome them. For example, you’ll discover when you really do need to pair IronPython with a static language to obtain the robust application performance and development environment that you need.

Who This Book Is For

This book is for the professional developer. While it does include introduction sections, the pace of the introductory material is quite fast and the novice developer will tend to become lost. The book does include all of the beginning IronPython you need such as working with variables and using loops, but this material consumes a relatively small portion of the book. The book assumes that you also have knowledge of the .NET Framework after working with another language such as C# or Visual Basic.NET. The examples do provide complete information on everything you need to include in the source code, so your knowledge of the .NET Framework doesn’t have to be extensive, but some knowledge is helpful.

What This Book Covers

Professional IronPython begins with an act of discovery. You’ll learn how IronPython can help you create better applications in less time and with fewer errors. To keep things balanced, you’ll also see where IronPython falls a bit short. The point is to provide a balanced view of what IronPython can do so you don’t start a project and experience nasty surprises. As part of this discovery process, you install IronPython on your system and begin building applications with it. The first applications are relatively simple and demonstrate the kinds of things every developer needs to know when starting a new language, such as how to work with structures.

After the introductions are over, the book begins looking at some of the ways in which you can use IronPython to build real applications. You’ll discover how to access both the Standard Library and the .NET Framework from IronPython. You’ll use your new knowledge to create Windows Forms applications, interact with COM objects, and work at the command line. In fact, you’ll even build an ASP.NET application using IronPython.

Next comes some advanced IronPython topics. Everyone needs to know how to work with XML, so that’s the first advanced topic you’ll tackle. The next advanced topic is the Dynamic Language Runtime (DLR) and you learn what it can do for you. Interestingly enough, you could build your own language using DLR, should you want to do so. The next few chapters discuss how to use IronPython with other .NET languages. First you see how to access IronPython from other languages, and then you discover how to build extensions for IronPython using both C# and Visual Basic.NET.

The last two chapters of the book are possibly the most interesting for someone who has worked with programming languages for a long time. Chapter 18 demonstrates how you can use IronPython to improve your testing process for just about any language. Of course, IronPython works best with .NET languages. Chapter19 discusses techniques for using IronPython on other platforms. The idea of writing an application just once and executing it equally well on Windows, Linux, and the Mac OS X is exciting.

How This Book Is Structured

This book is structured to discuss IronPython in a progressively complex manner. It doesn’t leave you wondering where the basics are — the first few chapters provide a whirlwind tour of the IronPython implementation of the Python language. However, by the end of the book you’ve discovered some very advanced information indeed. For example, you’ll create an IronPython extension that directly accesses the Win32 API. With this in mind, the following list provides you an overview of the book structure so you can find what you want quickly.

Part I: Introducing IronPython: This part of the book begins with an introduction to IronPython. You begin by obtaining and installing the software, using the IronPython console, and then creating your first application. The discussion continues by examining the modules that come with IronPython and working with some basics such as the standard input, output, and error devices. You also begin creating IronPython functions and performing other simple tasks.Part II: Using the IronPython Language: This part of the book provides a fast-paced tour of the IronPython language. You begin with simple statements, work through loops, examine arrays and collections, and then move on to structures and object. By the time you complete this part of the book, a professional developer will have enough information to write intermediate-level IronPython code.Part III: Working with IronPython: This part of the book begins the process of performing some real work with IronPython. It begins by examining both the Standard Library and the .NET Framework. You discover that it isn’t always possible to directly access everything you want, but you can access most items with relative ease. The chapters in this part of the book provide lots of tips and techniques for overcoming difficulties with IronPython. The discussion continues with chapters that examine specific application types: Windows Forms, COM interactions, command line applications used for administrative tasks, and ASP.NET applications. This part of the book ends with a complete discussion of debugging techniques — an essential part of using any programming language.Part IV: Advanced IronPython Topics: This part of the book goes beyond basic applications and moves into areas that are a little more exotic. The chapter on XML may not seem very interesting at first, but when you see the ease with which IronPython manipulates XML, you’ll really be impressed. The next topic is DLR, which is an exciting technology you can use for all kinds of tasks. Chapter 15 shows how to access your IronPython code from static languages such as C# and Visual Basic.NET. Chapters 16 and 17 show how to access C# and Visual Basic.NET code from IronPython. These three chapters together help you understand that IronPython isn’t an isolated language — you really can mix and match it with other languages as needed. Chapter 18 is possibly one of the most exciting chapters because it shows how you can use IronPython to perform application testing. Finally, Chapter 19 describes how you can use IronPython with Mono, a .NET Framework alternative that makes it possible to use your IronPython applications on other platforms.Appendices: This book contains two appendices that contain important information. You can probably skip them if you want, but the information is really helpful in bridging some gaps in IronPython functionality. Appendix A describes the differences between IronPython and CPython, both of which implement the Python language. Appendix B provides information about using CPython extensions with IronPython. CPython and IronPython don’t always work well together, but the information in these appendices can help you overcome any potential problems.

What You Need to Use This Book

Theoretically, all you need is a computer with Windows installed on it to work with IronPython. The computer must have a copy of the .NET Framework 3.5 or older installed on it that you can download from http://www.microsoft.com/NET/. Chapter 1 contains complete instructions for downloading and installing your copy of IronPython. You must also have a text editor — even Notepad will do, but it won’t be very convenient to use.

If you want to get full use out of this book, however, you must have a copy of Visual Studio.NET 2008 or above. The book examples rely on Visual Studio.NET 2010. You won’t be able to work with the examples later in the book unless you have a copy of Visual Studio. In addition, a number of the techniques, such as debugging, require that you have a copy of Visual Studio.NET. Nothing has been tested with the Visual Studio Express Edition products, and there’s no guarantee that anything will work with this edition of the product.

Conventions

To help you get the most from the text and keep track of what’s happening, we’ve used some conventions throughout the book. Typical examples follow:

Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

A warning tells you that something terrible will happen should a particular event occur. For example, if you perform a task incorrectly, you might see data loss.

As for styles in the text:

We highlight new terms and important words when we introduce them.We show keyboard strokes like this: Ctrl+A.We show filenames, URLs, and code within the text like so: persistence.properties. We show text you should type directly like this: type Hello for regular text and type MyFile.py for code and filenames.We show text that you should replace with your own values like this: MyName for regular text and MyVariable for code and filenames.We present code in the following way:

We use a monofont type with no highlighting for most code examples.

Source Code

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at http://www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-470-54859-2.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

Errata

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration and at the same time you will be helping us provide even higher quality information.

To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the Book Search Results page, click the Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors.

A complete book list including links to each book’s errata is also available at http://www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Errata page, click the Errata Form link and complete the form to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

p2p.wrox.com

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1. Go to p2p.wrox.com and click the Register link.

2. Read the terms of use and click Agree.

3. Complete the required information to join as well as any optional information you wish to provide, and click Submit.

4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

You can read messages in the forums without joining P2P but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

Part I: Introducing IronPython

CHAPTER 1: Discovering IronPythonCHAPTER 2: Understanding the IronPython Basics

Chapter 1: Discovering IronPython

WHAT’S IN THIS CHAPTER?

Understanding why you want to add IronPython to your developer toolboxObtaining and installing IronPython on your machineUnderstanding some underlying basics of how IronPython worksUsing IronPython at the console and within a windowDesigning and building a simple application

IronPython: It sounds like some kind of metal snake infesting your computer, but it isn’t. IronPython is the .NET version of the open source Python language (http://www.python.org/). Python is a dynamic language that can greatly enhance your programming experience, help you create applications in less time, and make the applications you create significantly more responsive to user needs. Of course, you’ve heard these promises before from other languages. This chapter helps you understand how IronPython delivers on these promises in specific situations. The smart developer soon learns that every language serves specific needs and might not work well in others. So this chapter isn’t here to blow smoke at you — once you complete it, you’ll understand the strengths and weaknesses of IronPython.

Of course, you’ll need to obtain a copy of IronPython before you can use it because Visual Studio doesn’t include IronPython as part of the default installation. This chapter helps you get IronPython installed on your system and tells you about some options you may want to install as well.

Once you have IronPython installed, you’ll want to know a little about how it works. This chapter won’t make you an IronPython guru who’s familiar with every nuance of the underlying structural elements, but it will give you a good overview that will make the rest of the book a lot easier to understand. You’ll put your new-found knowledge to the test by performing a few tasks at the IronPython console and within the IronPython windowed environment.

Finally, this chapter takes you through the process of creating a simple application. No, this isn’t going to be the next great Windows application. It will be a little better than Hello World, but not much. The idea is to get you started doing something useful with IronPython. Don’t worry; the examples will become a lot more interesting as the book progresses.

An Overview of IronPython

It surprises many developers to discover that computer languages are for humans, not for computers. A computer couldn’t care less about which language you use, because it’s all bits and bytes in the end anyway. Consequently, when you decide to learn another computer language, it really does pay to know what that language will do for you, the developer. Otherwise, there really isn’t a point in making the effort.

One phrase you often hear when discussing Python (and by extension, IronPython) is “batteries included.” Python has an immense standard library that addresses everything from working with ZIP files to interacting with the file system. You’ll discover the details of working with the Standard Library in Chapter 6. For now, it’s important to know that the Standard Library has a lot to offer and you may very well be able to build many of your applications without ever thinking about the .NET Framework.

As previously mentioned, IronPython is a .NET version of the Python language. For a .NET developer, using IronPython has the advantage of letting you create extensions using .NET (see Chapters 16 and 17 for details). In addition, you have full access to the .NET Framework (see Chapter 7 for details). You can work with IronPython and other .NET languages that you already know, which means that you can use the right tool for every job. However, IronPython has a few differences from the CPython implementation that everyone else uses (see Appendix A for details), which means that you can occasionally run into some odd compatibility problems when using IronPython. As with most things in life, advantages usually come with a few disadvantages.

You’ll see Python appear in many guises when you begin using it. The original implementation of Python is CPython and that’s the implementation that most developers target. In fact, you’ll often see IronPython compared and contrasted with CPython throughout this book. It’s important to remember that all these implementations attempt to achieve the same goal — full support of the Python standard. In most cases, all you really need to worry about is the IronPython implementation, unless you plan to use third-party libraries written for another Python implementation. This book helps you understand the use of CPython extensions in Appendix B.

There are some basic reasons that you want to use IronPython (or Python for that matter). The most important reason is that IronPython is a dynamic language, which means that it performs many tasks during run time, rather than compile time. Using a dynamic language means that your code has advantages of static languages, such as Visual Basic, in that it can more easily adapt to changing environmental conditions. (You’ll discover many other dynamic language advantages as the chapter progresses.) Unfortunately, you often pay for runtime flexibility with poorer performance — there’s always a tradeoff between flexibility and performance.

Performance is a combination of three factors: speed, reliability, and security. When an application has a performance hit, it means a decrease in any of these three factors. When working with IronPython, there is a decrease in speed because the interpreter must compile code at run time, rather than at compile time. This speed decrease is partially offset by an improvement in reliability because IronPython applications are so flexible.

Dynamic languages provide a number of benefits such as the ability to enter several statements and execute them immediately to obtain feedback. Using a dynamic language also provides easier refactoring and code modification because you don’t have to change static definitions throughout your code. It’s even possible to call functions you haven’t implemented yet and add an implementation later in the code when it’s needed. Don’t get the idea that dynamic languages are new. In fact, dynamic languages have been around for a very long time. Examples of other dynamic languages include the following:

LISP (List Processing)SmalltalkJavaScriptPHPRubyColdFusionLuaCobraGroovy

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 platformsManaged support using both Java and .NETConsiderable object-oriented programming (OOP) functionality that is easy to understand and useThe capability to look within the code — .NET developers will know this as a strong form of reflectionAn extensive array of standard librariesFull library support using hierarchical packages (a concept that is already familiar to every .NET developer)Robust third-party libraries that support just about every needSupport for writing both extensions and modules in both C and C++Support for writing extensions and modules using third-party solutions for both .NET (IronPython) and Java (Jython)Modular application developmentError handling through exceptions (another concept familiar to any .NET developer)High-level dynamic data typesEase of embedding within applications as a scripting solutionProcedural code that is relatively easy and natural to writeEase of reading and a clear syntax

All these features translate into increased developer productivity, which is something that dynamic languages as a whole supposedly provide (productivity is one of these issues that is hard to nail down and even harder to prove unless you resort to metrics such as lines of code, which prove useless when comparing languages). In addition to the great features that Python provides, IronPython provides a few of its own. The following list provides a brief overview of these features:

Full access to the .NET FrameworkUsability within Silverlight applicationsInteractive console with full dynamic compilation provided as part of the productAccessibility from within a browser (see http://ironpython.codeplex.com/Wiki/View.aspx?title=SilverlightInteractiveSession for details)Full extensibility using the .NET FrameworkComplete source code available (see http://ironpython.codeplex.com/SourceControl/ListDownloadableCommits.aspx for details)

One of the negatives of working with IronPython, versus Python (in the form of CPython), is that you lose support for multiple platforms — you only have direct access to Windows. You can get around this problem using Mono (http://www.mono-project.com/Main_Page), but it isn’t a straightforward fix and many developers will find it cumbersome. (Chapter 19 tells you more about working with Mono — a valuable solution for some Windows versions as well, such as Windows Server 2008 Server Core.) Of course, there isn’t any way to get around the lack of Java support — you simply choose one virtual machine or the other. Appendix A lists more IronPython differences from CPython, most of which will cause compatibility and other issues for you.

An interesting use of IronPython is as an application testing tool. In fact, some developers use IronPython exclusively for this purpose. Chapter 18 tells you more about this exciting use of IronPython and demonstrates that using IronPython for this purpose really does make application testing considerably easier.

Don’t get the idea that IronPython is going to restrict your use of familiar technologies. You can still create a Windows Forms application (see Chapter 8) and interact with COM (see Chapter 9). It’s even possible to create command line (console) applications (see Chapter 10) and work with the Internet (see Chapter 11) just as you always have. What IronPython provides is another way to view problems that you must address using your applications. As with most languages, what you’re getting is another tool that lets you create solutions in the least amount of time and with the fewest bugs.

Getting IronPython

Before you can use IronPython, you need to get a copy of your own, install it, and check to make sure it works. Theoretically, you might want to obtain the source code and build your own version of IronPython, but most developers simply download the binaries and begin working with IronPython right away. The first three sections that follow tell you what you need to work with IronPython, how to obtain the software, and how to install it. You’ll definitely want to read these sections.

The final two sections are completely optional. In fact, you may want to skip them for now and come back to them after you complete more chapters in the book. The first optional section tells you how to build your own copy of IronPython from the source. The second optional section tells you about third-party libraries.

There’s a huge base of third-party libraries for IronPython. Generally, you don’t need to install any third-party libraries to use this book. Everything you need to work with IronPython is included with the download you get from the CodePlex Web site. The only time you might need to work with third-party libraries is in Part IV. You’ll receive specific instructions in the Part IV chapters for any required third-party libraries, so you only need to read “Using Third-Party Libraries” if you plan to work with third-party libraries immediately.

Understanding the IronPython Requirements

As with any software, IronPython has basic system requirements you must meet before you can use it. It turns out that there are actually two versions of IronPython 2.6 — one for the .NET Framework 2.0, 3.0, and 3.5, and a second for the .NET Framework 4.0. Here are the requirements for the .NET Framework 2.0, 3.0, and 3.5 version.

The .NET Framework 2.0, 3.0, and 3.5(Optional) Visual Studio 2005 or Visual Studio 2008 (your system must meet the prerequisites for this software)(Optional) .NET Framework 2.0 Software Development Kit (SDK)

You need only the optional requirements if you plan to build IronPython 2.6 from the source code. Here are the requirements for the .NET Framework 4.0 version (again, the optional requirements are there if you want to build IronPython from source code).

The .NET Framework 4.0(Optional) Visual Studio 2010

Getting the Software

As with most open source software, you have a number of choices when it comes to downloading IronPython. For the sake of your sanity, the best choice when starting with IronPython is to download the binary version of the product from http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30315. You’ll see the Microsoft Installer (MSI) link right below the Recommended Download link as IronPython-2.6.msi. If you really must save the few seconds downloading the MSI version, select the IronPython-2.6-Bin.zip link instead.

It’s also possible to compile IronPython from the source code. If you want to use this option, select the IronPython-2.6-Src.zip link. You must have a copy of Visual Studio installed on your system to use this option. The “Building the Binaries from Scratch” section of the chapter describes how to build a version from scratch, but this process truly isn’t for the IronPython beginner and doesn’t serve much of a purpose unless you plan to add your own enhancements.

Most developers will likely use the standard version of IronPython that works with the .NET Framework 3.5 and earlier. However, you might need some of the new features in the .NET Framework 4.0, such as the C# dynamic keyword, which is part of the Dynamic Language Runtime (DLR) (http://dlr.codeplex.com/). The section “Understanding the Dynamic Language Runtime” later in this chapter tells you more about this .NET 4.0 feature. You can obtain this version of IronPython at http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27320. The examples in this book will work with either version of IronPython 2.6, except where noted (where I’m demonstrating how to work with the DLR).

Performing the Installation

This section assumes that you’ve downloaded the MSI file to make life easy for yourself. This procedure works equally well for either version of IronPython 2.6 so you can use it for a DLR install as well. The following instructions help you get IronPython installed on your machine.

1. Double-click the MSI file you downloaded from the CodePlex Web site. You’ll see the usual Welcome page — click Next to get past it.

2. Read the licensing agreement, check I Accept the Terms in the License Agreement, and then click Next. You’ll see the Custom Setup dialog box shown in Figure 1-1 where you can select the IronPython features you want to install. At a minimum, you must install the Runtime. The Documentation, Standard Library, and Tools features are also strongly recommended. This book assumes that you’ve installed all the features. However, you might want to install just those features you actually need for a production setup (you might not actually need the samples).

Figure 1-1: Choose the features you want to install.

When you perform a DLR installation, you’ll see a Do Not NGen Installed Binaries option on the Custom Setup dialog box. Using the Native Image Generator (NGen) can greatly improve application performance, as described at http://msdn.microsoft.com/en-us/magazine/cc163610.aspx. Earlier versions of IronPython didn’t use NGen to build the libraries for you by default. You had to use a special command line to obtain the NGen feature (msiexec /qn /i "IronPython.msi" NGENDLLS=True). The default setup for IronPython 2.6 is to use NGen to build the libraries.

However, using NGen also binds the binaries to the local machine, which may not be what you want when working in a dynamic environment. Consequently, if you plan to use DLR more than you plan to use other IronPython features, you might want to check the Do Not NGen Installed Binaries option.

3. Select the features you want to install. Click Next. You’ll see a summary dialog box that simply states you’re ready to install IronPython.

4. Click Install. MSI will begin the installation process. At some point, you’ll see an installation completion screen.

5. Click Finish. You should be ready to begin working with IronPython at this point.

Building the Binaries from Scratch

You may eventually want to build the IronPython binaries from scratch. The normal reason to perform this task is to create a special version of IronPython that meets specific needs. A company may want to add extensions or special features to IronPython. Because you have the source code, it’s acceptable to create a custom version of IronPython for yourself — one that contains any feature set you deem necessary to get your work completed. So have fun molding IronPython and then sharing your modifications with others. In order to perform this task, you must have a copy of Visual Studio (you must have Visual Studio 2010 to build a DLR version of IronPython). The following steps tell you how to build the IronPython 2.6 binaries from scratch.

1. Download the source code file, such as IronPython-2.6-Src.zip.

2. Extract the files into a folder. The example assumes that you extracted the files into the root directory of your hard drive into \IronPython-2.6.

3. Locate the \IronPython-2.6\Src directory and open the IronPython.sln solution using Visual Studio. Visual Studio will load the required files, and you’ll see them in Solution Explorer, as shown in Figure 1-2. Figure 1-2 shows that IronPython consists of a number of projects — you must compile the entire solution to obtain a workable group of DLLs.

Figure 1-2: IronPython consists of multiple projects, so you must compile the entire solution.

4. Make any required changes to the source code.

5. Choose Build ⇒ Build Solution. Visual Studio creates the required DLLs, ready for testing.

Using Third-Party Libraries

Python is an extremely flexible language and enjoys strong third-party support. In fact, you can find lists of these libraries in various places on the Internet. Here are a few places to check:

http://code.google.com/appengine/docs/python/tools/libraries.htmlhttp://www.amaltas.org/show/third-party-python-libraries-and-frameworks.htmlhttp://dakrauth.com/blog/entry/third-party-python-libraries-interest/

IronPython is a complex product. If you fail to compile the entire solution every time you make a change, you could end up with an unworkable group of DLLs due to interactions. It’s important to build everything so that any changes propagate properly.

You should be able to use some third-party libraries with IronPython. At the time of this writing, you won’t actually find any usable third-party libraries. However, you should checkhttp://www.ironpython.info/index.php/Third-Party_Library_Compatibility from time-to-time to discover whether there are any third-party libraries that do work with IronPython. It’s important to note that this list represents only tested libraries — you may find other third-party libraries that do work with the current version of IronPython.

Understanding the Dynamic Language Runtime

IronPython is a dynamic language, yet the Common Language Runtime (CLR) is a static environment. While you can build a compiler that makes it possible to use a dynamic language with CLR, as was done for IronPython 1.0, you’ll find that certain functionality is missing because CLR simply doesn’t understand dynamic languages. Consequently, Microsoft started the Dynamic Language Runtime (DLR) project (see http://dlr.codeplex.com/ for additional information). DLR sits on top of CLR and performs a level of interpretation that offers additional functionality for dynamic languages. By relying on DLR, IronPython gains access to the following support:

Shared dynamic type supportShared hosted modelQuick dynamic code generationInteraction with other dynamic languagesImproved interaction with static languages such as C# and Visual Basic.NET (see Chapters 15, 16, and 17 for details)Shared sandbox security model and browse integration

DLR is now part of the .NET Framework 4.0. (In fact, you’ll discover the details of this integration in Chapter 14.) Consequently, you can begin accessing these features immediately when using Visual Studio 2010 without having to install any additional support. Microsoft currently supports these languages using DLR:

IronPythonIronRubyJavaScript (EcmaScript 3.0)Visual Basic

Silverlight also provides support for DLR and there’s even a special SDK for Silverlight DLR. You can discover more about this SDK at http://silverlight.net/learn/dynamic-languages/. The relevance of Silverlight support for this book is that you can now use IronPython as part of your Silverlight solution as described in Chapter 11. You can summarize the benefits of using DLR as follows:

Makes it easier to port dynamic languages to the .NET FrameworkLets you include dynamic features in static languagesCreates an environment where sharing of objects and libraries between languages is possibleMakes it possible to perform fast dynamic dispatch and invocation of objects

This section provides a good overview of DLR. You’ll discover additional details about DLR as the book progresses. However, if you’d like to delve into some of the architectural details of DLR, check out the article at http://msdn.microsoft.com/library/dd233052.aspx.

Using the IronPython Console

The IronPython console is the best place to begin working with IronPython. You can enter a few statements, test them out, and then work out additional details without too many consequences. In addition, because the console is interactive, you obtain immediate feedback, so you don’t have to wait for a compile cycle to discover that something you’re doing is completely wrong. In fact, even after you’ve mastered IronPython, you’ll find that you use the console to try things out. Because IronPython is a dynamic language, you can try things without worrying about damaging an application. You can test things quickly using the console and then include them in your application. The following sections describe the IronPython console and how to use it. Expect to see the IronPython console in future chapters.

Opening and Using the Default Console

The IronPython console is an application provided with the default installation. You access it using the Start ⇒ Programs ⇒ IronPython 2.6 ⇒ IronPython Console command. The console, shown in Figure 1-3, looks something like a command prompt, but it isn’t.

Figure 1-3: The IronPython console looks something like a command prompt.

Notice that the top of the window tells you which version of IronPython you’re using and which version of the .NET Framework it’s running on. This is important information because it helps you understand the IronPython environment and what limitations you have when working with IronPython. Below this first line, you’ll see some commands that Microsoft thought you might find useful. The “Getting Help with Any Function” section of the chapter tells you more about the Help command.

To use the console, simply type the commands you want to issue. When you’re done, IronPython will execute the commands and output any result you requested. A command need not be a function call or an object instantiation as it is in other languages. For example, type 2 + 2 right now and then press Enter. You’ll see the result of this simple command, as shown in Figure 1-4.

Figure 1-4: IronPython is dynamic and the console is interactive.

Whenever you want to end a particular task, such as working with Help, press Enter a second time. The console will take you to the previous level of interaction.

Getting Help with Any Function

You can get help with any function in the console. If you simply type help and press Enter in the console, IronPython tells you how to request interactive help or help about a specific object. To begin interactive help, type help() and press Enter. You’ll see the interactive help display shown in Figure 1-5.

Figure 1-5: Interactive help lets you ask questions about IronPython.

Let’s say you have no idea of what you want to find. Console help provides you with a list of words you can type to get general help. These terms are:

ModulesKeywordsTopics

Type any of these terms and press Enter. You’ll see a list of additional words you can type, as shown in Figure 1-6 for modules. Using this technique, you can drill down into help and locate anything you want. In fact, it’s a good idea to spend some time in help just to see what’s available. Even advanced developers can benefit from this approach — I personally follow this approach when I have time to increase my level of knowledge about all of the languages I use.

IronPython will constantly refer you to the online help for Python. So you might as well check it out now. You’ll find a good Python tutorial at http://docs.python.org/tutorial/. While you’re at it, there’s also a good IronPython-specific tutorial that comes with your installation. Simply choose Start ⇒ Programs ⇒ IronPython 2.6 ⇒ IronPython Tutorial. Although these sources of help are useful, you’ll get a much better start working through the examples in the book.

You might know about the topic you want to find. For example, you might know that you want to print something to screen, but you don’t quite know how to use print. In this case, type help('print') and press Enter. Figure 1-7 shows the results. You see complete documentation about the print keyword.

Understanding the IPY.EXE Command Line Syntax

When you open a console window, what you’re actually doing is executing IPY.EXE, which is the IronPython interpreter. You don’t have to open a console window to use IPY.EXE. In fact, you normally won’t. It’s possible to execute IronPython applications directly at the command line. The following sections discuss IPY.EXE in more detail.

Adding IPY.EXE to the Windows Environment

Before you can use IPY.EXE effectively, you need to add it to the Windows path statement. The following steps provide a brief procedure.

1. Open the Advanced tab of the Computer (or My Computer) applet.

2. Click Environment Variables. You’ll see an Environment Variables dialog box.

3. Highlight Path in the System Variables list. Click Edit. You’ll see the Edit Environment Variable dialog box.

Figure 1-6: Drill down into help to find topics of interest.

Figure 1-7: The console also provides the means to obtain precise help about any module, keyword, or topic.

4. Select the end of the string that appears in the Variable Value field. Type ;C:\Program Files\IronPython 2.6 and click OK. Make sure you modify this path to match your IronPython configuration.

5. Click OK three times to close the Edit System Variable, Environment Variables, and System Properties dialog boxes. When you open a command prompt, you’ll be able to access the IronPython executables.

Executing an Application from the Command Prompt

Normally, you execute an application by typing IPY <Python Filename> and pressing Enter. Give it a try now. Open a command prompt, type CD \Program Files\IronPython 2.6\Tutorial, and press Enter. You’re in the sample files supplied by IronPython. Type IPY WFDemo.py and press Enter. You’ll see a window displayed. When you click your mouse in the window, you see the word Hello displayed at each click point, as shown in Figure 1-8. If you look at the command prompt window at this point, you’ll see that the mouse cursor is blinking but you can’t type anything because the command prompt is waiting for the IronPython interpreter to end. When you click the Close button, the application ends and you can again type something at the command prompt.

Understanding the IPY.EXE Standard Command Line Switches

Figure 1-8: The WFDemo shows that you can create windowed environments for IronPython applications.

Sometimes you need to provide IPY.EXE with more information about a particular application. In this case, you can use one of the command line switches shown in the following list to provide IPY.EXE with the required information. It’s important to note that the command line switches are case sensitive; –v isn’t the same as –V.

–3: Forces the interpreter to warn about Python 3 compatibility issues in your application.

–c cmd: Specifies a command you want to execute. This command line switch must appear last on the line because anything after this command line switch is interpreted as a command you want to execute. For example, if you type ipy -c "print ('Hello')", the interpreter will output the word Hello.

–D: Enables application debugging.

–E: Ignores any environment variables that you specified as part of the Windows environment variable setup or on the command line after you started it. Some applications may not run after you use this command line switch because they won’t be able to find modules and other files they need.

–h: Displays a complete list of the command line arguments.

–i: Displays the console after running the script. You can then inspect the results of the script using console commands.

–m module: Runs library module as a script.

–O: Tells the interpreter to generate optimized code, which means you can’t perform debugging, but the application will run faster.

–OO: Removes all of the doc strings and applies –O optimizations so that the application runs even faster than using the –O command line switch alone.

–Q arg: Specifies use of one of several division options. You can use any of these values.

–Qold (default): The precision of the output depends on the operators used. For example, if you divide two integers, you get an integer as output.–Qwarn: Outputs warnings about a loss of precision when performing division using integers.–Qwarnall: Outputs warnings about all uses of the classic division operator.–Qnew: The output is always a precise floating point fraction.

–s: Specifies that the interpreter shouldn’t add the user site directory to sys.path.

–S: Specifies that the interpreter shouldn’t imply that it should execute the import site command on initialization.

–t: Outputs warnings about inconsistent tab usage, which can lead to code interpretation problems.

–tt: Outputs errors for inconsistent tab usage. Inconsistent tab usage can lead to code interpretation problems, which can result in hard-to-locate bugs.

–u: Provides unbuffered stdout and stderr devices. Typically, the interpreter uses buffering to provide better application performance.

–v: Specifies that the interpreter should provide verbose output, which means that you can see everything going on in the background. You can also obtain this result by using PYTHONVERBOSE=x (where x is a True or False environment variable).

–V: Prints the version number and exits. This option is useful when you want to be sure you’re using the correct version of IronPython for your application.

–W arg: Defines the kind of warning control. Specifying these command line switches tells the interpreter to add the specified warning messages to the output. (Don’t worry too much about these warnings — you learn more about them in Chapter 12.) You can use any of these values:

–Waction: Actions are one of the following strings: error (turns matching warnings into exceptions), ignore (never prints matching warnings), always (always prints matching warnings), default (prints the first occurrence of a warning for each location where the interpreter issues the warning), module (prints the first occurrence of a warning for each module where the error occurs), and once (prints only the first occurrence of a warning no matter where it appears).–Wmessage: Messages are Regular Expressions that define which warning messages to match.–Wcategory: Categories specify the class of the warning message.–Wmodule: Modules are Regular Expressions that define which module to match.–Wlineno: Line numbers are integer values that specify a line number to match. Using 0 matches all line numbers.

–x: Skips the first line of the source code, which may have special instructions that you don’t need for the current session.

IronPython doesn’t support all of the CPython command line switches. Consequently, you may find that a batch file written to execute a CPython application won’t work properly with IronPython. For example, IronPython doesn’t appear to support the PYTHONHOME environment variable. All IronPython environment variables begin with IRON, so you need to modify batch files to include this first word as part of any environmental variable setup.

Working with the –X: Command Line Switches

In addition to the standard command line switches, you also have access to the –X: command line switches, which configure the IronPython interpreter. The following list describes each of the configuration options:

–X:AutoIndent: Enables auto-indenting in the read-evaluation-print loop (REPL).

–X:ColorfulConsole: Enables ColorfulConsole support.

–X:Debug: Enables application debugging. This option is preferred over the –D command line switch because it’s newer and will enjoy a longer support period.

–X:EnableProfiler: Enables profiling support in the compiler, which helps you optimize your applications.

–X:ExceptionDetail: Enables ExceptionDetail mode, which gives you more information about every exception that occurs, making it easier to locate the source of the problem (but filling the screen much faster as well).

–X:Frames: Enables basic sys._getframe() support.

–X:FullFrames: Enables sys._getframe() with access to local objects and variables.

–X:GCStress: Specifies the garbage collector (GC) stress level. Stressing the GC can point out potential resource problems in your application.

–X:LightweightScopes: Generates optimized scopes that are easier for the GC to collect. Optimizing GC functionality tends to improve the overall performance (both speed and reliability) of your application.

–X:MaxRecursion: Determines the maximum recursion level within the application. Recursion can use a lot of system resources, so controlling the amount of recursion tends to reduce resource usage by applications that rely on recursion. Of course, reducing the recursion levels can also cause application exceptions.

–X:MTA: Runs the application in a multithreaded apartment (MTA).

–X:NoAdaptiveCompilation: Disables the adaptive compilation feature.

–X:PassExceptions: Tells the interpreter not to catch exceptions that are unhandled by script code.

–X:PrivateBinding: Enables binding to private members.

–X:Python30: Enables available Python 3.0 features, such as classic division (where dividing two integers produces an integer result).

–X:ShowClrExceptions: Displays the Common Language Specification (CLS) exception information.

–X:TabCompletion: Enables TabCompletion mode.

–X:Tracing: Enables support for tracing all methods even before the code calls sys.settrace().

Modifying the IPY.EXE Environment Variables

IPY also supports a number of environment variables. The following list describes each of these environment variables.

IRONPYTHONPATH: Specifies the path to search for modules used within an application

IRONPYTHONSTARTUP: Specifies the name and location of the startup module

Exiting the IronPython Interpreter

Eventually, you’ll want to leave the console. In order to end your session, simply type exit() and press Enter. As an alternative, you can always press Ctrl+Z and then Enter. The console will close.

Using the IronPython Windowed Environment

IronPython also provides access to a windowed environment, but you can’t access it from the start menu. Instead, you must provide a shortcut to the file you want to run or open a command prompt and start the application manually. The windowed environment simply provides a GUI interface for working with IronPython, but doesn’t do anything else for you. You start the windowed environment by using IPYW.EXE. If you type IPYW and press Enter, you see the command line switch help shown in Figure 1-9.

Figure 1-9: The windowed version supports the same features as the command line version.

As you can see from Figure 1-9, the windowed environment supports the same command line switches as the character mode command line version. However, you can’t use the windowed environment to run the interpreted console environment, which is a shame because many developers would prefer working in the nicer environment. To see that the windowed environment works the same way as the standard console, type IPYW WFDemo.py and press Enter. You’ll see the test application shown earlier in Figure 1-8.

Creating Your First Application

After all this time, you might have started wondering whether you would get to write any code at all in this chapter. The first application won’t be very fancy, but it’ll be more than a simple Hello World kind of application. You can use any editor that outputs pure text in this section. Notepad will work just fine. Listing 1-1 shows the code you should type in your editor.

Listing 1-1: A simple first application that multiplies two numbers

def mult(a, b):

    return a * b

print('5 * 10 ='),