A

Abbreviations def, functions sorting keys Abstract Windowing Toolkit (AWT) module AbstractFormatter(writer) class connection objects , 2nd exception states methods and properties objects actual(options) method add(filename, ) method add(type, options) method add cascade(options) method add command(options) method add flowing data(data) attribute add hor rule(*args, **kw) attribute add label data(format, counter) attribute add line break() attribute add literal data(data) attribute add...

About the Author

I decided to follow an IT career when I was just 11 years old that happened the day I first saw a real computer well, actually it was just a TK85. On my next birthday after that fateful day, I got a TK90X. Then came the MSX, 386, 486, and so forth. This long-time background has opened many doors (and Windows ) to me. I got both my graduate and my post-graduate degrees in the computer field. At this time, I am an IT consultant with little more than eight years...

Accessing Generic DLLs

Sam Rushing has created an extension module called calldll that enables Python to call any function that is part of a Windows DLL. It doesn't matter whether the DLL is a Python extension. The problem to remember is that errors caused by non-Python extension DLLs don't return exception codes but error messages. With this module you can call any function in any DLL. This means that you can do just about anything on Win32. This module includes a library that gives access to lots of the system GUI...

An Introduction to CGI

CGI (Common Gateway Interface) is a standardized way for the Web Server to invoke an external program to handle the client request. It is possible for the external program to access databases, documents, and other programs as part of the request, as well, and present customized data to viewers via the Web. A CGI script can be written in any language, but here, of course, we are using only Python. CGI enables you to handle from the low end of mail-forms and counter programs to the most complex...

AOLserver Web Server

This is a Web Server created and used by AOL. Note that anyone using AOLserver would be better off learning TCL. For details, see The project that embeds Python in the AOLServer Web Server, is now semi-stable for simple CGI-style operations, and provides a 4-5x speedup over the straight CGI. Check it out at http pywx.sourceforge.net. Microsoft IIS and PWS You can set up both Microsoft IIS Server and Personal Web Server (PWS) to call the Python interpreter to handle Python CGI scripts.

Binary Data The struct Module

The struct module is largely used to manipulate code of platform-independent binary files. It is a good choice for handling small files. For large files, you should consider using the array module. Binary data files are much less likely to be platform independent. Also, it is easier to extend a text file format without breaking compatibility. The struct module works by converting data between Python and binary data structures, which normally interact using functions written in C. This module...

BuiltIn Data Types

Built-in data types are types that are already built into the interpreter. They are divided into two groups Immutable Data Types These objects cannot have their values altered (for example, strings, numbers, and tuples). These objects can have their values manipulated (for example, lists and dictionaries). Sometimes, it becomes necessary to assign a null value to a variable using the special data type known As you could see, nothing was returned. However, if you try to print this value, the...

Chapter Extending and Embedding Python

What is your name What is your quest What is your favorite color The information provided in this chapter is a big step for those who want to be highly specialized in Python programming. It demonstrates how you can create Python extension modules in C and C++, and how you can embed Python objects in other non-Python applications. Last updated on 1 30 2002 Python Developer's Handbook, 2002 Sams Publishing

Chapter Language Review

Spam spam spam spam spam spam spam and spam This chapter offers a complete review of the Python programming language. After you finish reading it, you will understand and master the concepts of this language. Furthermore, you will learn everything that is necessary to write useful Python programs. Last updated on 1 30 2002 Python Developer's Handbook, 2002 Sams Publishing 2002, O'Reilly & Associates, Inc. 2002, O'Reilly & Associates, Inc. Web Development > Python Developer's Handbook...

Chapter Python Libraries

All right, it's a fair cop, but society is to blame. This chapter shows what main module services and extensions are currently available for the Python programming language. The focus here is to expand your knowledge by introducing the most used modules and listing some examples for you. Last updated on 1 30 2002 Python Developer's Handbook, 2002 Sams Publishing 2002, O'Reilly & Associates, Inc. 2002, O'Reilly & Associates, Inc. Web Development > Python Developer's Handbook > 3....

Class Instances

A class instance is a Python object, and similar to every Python object, it has the following properties identity, object type, attributes, methods, and value. I will use the following class definition as the basis for the next explanations. First, let's declare the c class, and then we will create an instance of this class called obj. def _init_(self, value None) > > > obj.name Andre The identity is the memory location allocated for the object. It can be identified by using the id()...

Code Examples

Next, you have some code examples that demonstrate the concepts illustrated by this chapter. HTML Parsing Tool (File parsing.py) We are going to use the exchange.html as the source of information for this program. The idea is to read the file, replace all the occurrences of the domain name lessaworld for bebemania, and add hyperlinks for all email and Web pages references that exist there. < TITLE> Exchange Rates Home Page< TITLE> < b> List of current files that we have available at...

Cool SQL Language Web Pages

The Introduction to Structured Query Language site can be found at Several links to SQL material can be found at PostgreSQL Databases PostgreSQL is a free (open-source) SQL database. It is a sophisticated Object-Relational database system derived from Postgres4.2. It conforms to (most of) ANSI SQL and offers many interesting capabilities, including subselects, transactions, and user-defined types and functions. It is the most advanced open-source database available anywhere. Commercial Support...

Creating Userdefined Exceptions

Python allows you to create your own exceptions by subclassing any standard Python exception. Take a look at Chapter 5, Object-Oriented Programming, for more details about working with classes. > > > class ConfigError (exceptions.Exception) def _init_(self, arg None) raise ConfigError(Bad hostname) except ConfigError, e print e.args The import statement from the previous example isn't really necessary because the exceptions module contents are automatically imported by the interpreter....

CTC Cut The Crap by Constantinos Kotsokalis

This is a http proxy software written in Python, which cuts advertisement banners from your Web browser display. http softlab.ntua.gr ckotso CTC Alfajor, by Andrew Cooke Alfajor is an HTTP cookie filter, written in Python with an optional GUI. It acts as an HTTP proxy (you must configure your browser to use it) and can either contact sites directly or work with a second proxy (for example, a cache). Note that Alfajor does not fully conform to any HTTP version. However, in practice, it works...

DBAPI Specification v

The following specification is available online at Comments and questions about this specification can be directed to the SIG for Database Interfacing with Python at the email address db-sig python.org. For more information on database interfacing with Python and available packages, see the Database Topics Guide at http www.python.org. This document describes the Python Database API Specification 2.0. The previous version 1.0 is still available online at the Python Web site as a reference....

Debugging and Testing Your Script

Before putting your CGI scripts online, you need to be sure that they are working fine. You have to test them carefully, especially in near bounds and out of bounds conditions. A script that crashes in the middle of its job can cause large problems, such as data inconsistency in a database application. This is why you would use a transaction when updating a database from a cgi script (if it was deemed important enough). You should eliminate most of the problems by running your script from the...

Extending and Embedding Python

Python has the capability to glue applications together. No doubt this is one of Python's most important and well-known features. The reason for that is mostly because Python provides a two-way communication channel to C by supporting both embedding and extending functionality. Whenever you use Python code to call C code, you are extending Python. On the other hand, if you use C code to call Python code, you are embedding Python. Even though these features can bring great results to your...

Generic Operational System

This group of services provides interfaces to operating system features that you can use in almost every platform. Most of Python's operating system modules are based on the Posix interface. The os module is a portable OS API that searches for Operating-System-dependent built-in modules (mac, posix, nt), and exports their functionality using the same interface. Certain tools are available only on platforms that support them. However, it is highly recommended that you use this module instead of...

Handling Email Services

The smtplib module provides a low-level client interface to the SMTP protocol that can be used to send emails to any machine in the Internet that has an SMTP or ESMTP listener daemon. An example of this is as follows import smtplib import string host localhost fromclause alessa bebemania.com.br toclause rtaveira bebemania.com.br, jp alugueaqui.com.br toclause string.splitfields(toclause, ,) msgbody This email brings good news for you Best Regards SMTPServer.sendmail(fromclause, toclause,...

Httpwwwdigicoolcom Persistent CGI

Persistent CGI architecture provides a reasonably high-performance, transparent method of publishing objects as long running processes via the World Wide Web (WWW). The current alternatives to CGI that allow the publishing of long-running processes, such as FastCGI and ILU, have some level of Web server and platform dependencies. Persistent CGI allows a long running process to be published via the WWW on any server that supports CGI, and requires no specific support in the published...

If you need to quit the interpreter while working on UNIX or MS Windows systems press CTRLD or CTRLZ respectively

Last updated on 1 30 2002 Python Developer's Handbook, 2002 Sams Publishing < BACK Make Note Bookmark CONTINUE > command line interpreter 2nd applications hello world command line interpreter 2nd 3rd hello world program interpreters command line interpreter 2nd opening command line interpreter 2nd programs command line interpreter 2nd secondary prompts shell environment 2nd 3rd software 2002, O'Reilly & Associates, Inc. Until now, all the examples were written directly in the interpreter...

Index terms contained in this section

Identifying number of arguments, functions identifying number of arguments, functions abbreviations calling functions without functions assigning identifying number of arguments, functions functions without arguments changing global variables inside functions commands return def abbreviation, functions default arguments dynamic namespaces editing global variables inside functions format functions functions 2nd 3rd 4th 5th assigning to variables calling without arguments changing global...

Introduction to TclTk

Tk is a popular and endorsed toolkit developed by John Ousterhout that can handle windows, GUI events, and user interactions. This toolkit is provided as an extension for Tcl. That is why part of Tkinter is an interface to Tcl. Without these routines, the management of a GUI environment would require an application with many lines of code. The toolkit was originally developed at the University of California, Berkeley, to be a supplement to Tcl (a language also developed by Ousterhout). After...

Macintosh Environment

MacPython is a Python version available for the Macintosh. Jack Jansen maintains it, and you can have full access to the entire documentation at his Web site. Currently, version 1.5.2 is available for download at http www.cwi.nl jack macpython.html. Beta versions from version 1.6 are also available. You can also download this distribution at Python's official Web site at http www.python.org download download mac.html. The full distribution is available in one unique file that also contains...

MailmanGNU Mailing List Manager

Mailman is a Web integrated mailing list manager that helps manage email discussion lists, much like Majordomo and Smartmail. Unlike most similar products, Mailman gives each mailing list a Web page, and allows users to subscribe, unsubscribe, and so on, over the Web. Even the list manager can administer his list entirely from the Web. Both users and system administrator can do almost everything through an Internet connection. Mailman also integrates most things people want to do with mailing...

Metaclasses

A metaclass is just a class that is used as a template to create class-like entities. Normally, you create instances based on classes. The goal here is to create classes (metainstances) based on other classes (metaclasses). The resulting metainstances are used as base classes for your own classes. The whole idea is to offer you the possibility of operating Python's internal class-handling engine. Everything that usually happens behind the scenes while manipulating your classes and objects now...

MIME Parsing and Manipulation

MIME (Multipurpose Internet Mail Extensions) is a standard for sending multipart multimedia data through Internet mail. This standard exposes mechanisms for specifying and describing the format of Internet message bodies. A MIME-encoded message looks similar to the following Content-Type multipart mixed Date Mon, 03 Apr 2000 18 30 23 -0400 From Andre Lessa < alessa lessaworld.com> To Renata Lessa < rlessa lessaworld.com> Content-Type text plain charset us-ascii Sorry Honey, I am late...

More Sources of Information

PyVersant is a simple Python wrapper for the Versant commercial OODBMS. By using PyVersant in the Python command prompt, you can interactively find objects, look at their values, change those values, and write the object back to the database, among other things. More information is provided at the following site Details about Versant OODBMS are shown at the following site The Zope Object Database is a persistent-object system that provides transparent transactional object persistence to Python...

Networking Concepts

Networking systems are well-defined by the OSI ISO (Open Systems Interconnection International Standards Organization) seven-layer model, which suggests the following levels of the networking process physical, data link, network, transport, session, presentation, and application. However, keep in mind that, in practice, protocols span multiple layers, and you shouldn't worry if your application doesn't fit in this model. Most of today's networking stacks (including TCP IP) use less layers that...

Newsgroups Telnet and Gopher

The nntplib module implements a low-level interface to the client side of the NNTP (NetworkNews Transfer Protocol) protocol a service mostly known for providing newsgroups. This protocol is text-based because all the communication between the client and the server uses ASCII text. This protocol is also used to exchange Usenet news articles between servers. Newsgroups are organized hierarchically, according to their levels, which are separated by dots. In comp.lang.python for example, comp...

Patches and Bugs List

In case you notice something bizarre happening while you are coding, you can check it out in order to find out whether it is a bug or not. A query tool is provided by Python's official Web site to enable searches in the bug's list. Go to http www.python.org search search bugs.html and perform your search. You will be able to identify which bugs are opened, resolved, and so on. If you think that you might have caught a new bug, you can fill out a form to let the developer's team know about it....

Python GUI Toolkits

Choosing a toolkit for your graphical user interface (GUI) projects is not a simple thing. You need to research and compare what the features are that each option has to offer. When you decide to stick to one toolkit, you'd better be prepared to use it for some time. Toolkit implementations are so different that it becomes hard to change your code and your way of thinking from one toolkit to another whenever it comes time to move to a different implementation. Most of all, if you always jump...

Python Services

This first group of modules is known as Python Services. These modules provide access to services related to the interpreter and to Python's environment. The sys module handles system-specific parameters, variables, and functions related to the interpreter. sys.argv This object contains the list of arguments that were passed to a program. If you pass arguments to your program, for example, by saying, you are able to access those arguments by retrieving the value of sys.argv > > > import...

Python Versus Perl

Python is easier to learn than Perl, and it presents a more readable code. Perl is an excellent language too. Perl is great for work that requires text manipulation and data extraction, and it is also a great language for system administrators. The Windows distribution of Perl is apparently pretty good, so it can be used productively under Windows. However, Perl is much more productive when used in a UNIX environment. Python's productivity is platform-independent. Another important difference...

Python XML Package

For those who want to play around with XML in Python, there will be a Python XML package to serve several purposes at once. This package will contain everything required for basic XML applications, along with documentation and sample code basically, something easy to compile and install. A release candidate of the latest release of this package is now available as PyXML-0.5.5.tar.gz (GPG signature), dated June 5, 2000. This version contains SAX, the Pyexpat module, sgmlop, the prototype DOM...

Regular Expressions

We already know that the string module is used to apply basic manipulation operations on strings meanwhile, at the time of developing advanced routines, you might need to enhance Python's string-processing capabilities. That's when you should consider using the re module (re stands for regular expression). Regular expressions are strings, which contain a mix of text and special characters, that let you define complicated pattern matching and replacement rules for other strings. Some of the...

Selecting the Information

In a relational database, data is stored in tables. In our example, we have the USERS Table. ID, NAME, EMAIL, and AGE are the columns of this table. Now, say that you want to know the EMAIL and the AGE of each user. You have to use the SELECT statement as follows The following list is the result of your query Let me explain to you what you have done you asked to see all the rows from the USERS table, filtering only the EMAIL and AGE columns. Note that column names and table names do not have...

Sending Information to Python Scripts

Every time you use a URL to carry information to a CGI script, the data is transported as name value pairs, separated by ampersands (& ), and each pair is separated by an equal sign ( ). Whitespaces between words are usually converted to the plus symbol (+). Special characters are encoded to hexadecimal format ( HH) and preceded by the percent sign. Therefore, the string Parrot sketch is passed to the script as Parrot 20sketch. As you can see, the previous example is implicitly using the GET...

Site Management Tools

The following Python tools are used to manage Web sites. They implement several functions that simplify the daily tasks performed by webmasters, such as dead link checking, and object publishing. WebDAV (World Wide Web Distributed Authoring and Versioning) is a set of extensions to the HTTP 1.1 protocol, which allows users to collaboratively edit, manage, and update files safely on remote Web servers. It was developed by the WebDAV working group of the Internet Engineering Task Force (IETF)....

Step

Place your scripts in your cgi-bin directory. Step 14. If you are using an UNIX system, make sure that the first line of your script contain a shebang to identify the location of the Python interpreter. Step 15. Optionally, you can configure the server to run scripts only from the cgi-bin directory by replacing the following line in the access.conf file < Directory path to your httpd cgi-bin> Options Indexes FollowSymLinks < Directory> < Directory path to your httpd cgi-bin> Options...

Summary

This chapter exposes the extending and embedding functionality that gives Python the credit of possessing the capability to glue applications together. Whenever you use Python code to call C code, you are extending Python. On the other hand, if you use C code to call Python code, you are embedding Python. Python has a good relationship with C because Python's interpreter is written in C, and since its beginning, the interpreter has been ready to work with extension modules. The extension...

SWIGThe Simple Wrapper Interface Generator

SWIG (Simple Wrapper and Interface Generator) is an automated tool create by David Beazley used to write interfaces between Python and existing C libraries. These interfaces can contain several single functions. The programmer doesn't have to write any special wrapping functions to provide the glue between the Python scripting language and the C functions. SWIG works by reading an interface file that contains function and method prototypes. It automatically does the necessary type conversion,...

Table Formatting Operators Table

Hexadecimal integer (uppercase letters) floating point where the exponent is less than -4 or greater than the precision any printable object (such as strings) The following code is another simple example > > > print The value is d value The value is 14 Next, you will see some special ways to format operations by putting special characters between the literal and the formatting operator. Before going through the examples, we need to initialize some variables. > > > fltn 13.142783 >...

The Formatter Interface

Interfaces to create formatters are dependent on the specific formatter class being instantiated. The interfaces described as follows are the required interfaces, which all formatters must support once One data element is defined at the module level AS_IS. This value can be used in the font specification passed to the push_font() method described in the following, or as the new value to any other push_property() method. Pushing the AS_IS value allows the corresponding pop_property() method to...

The other modules

It is important to stick to the naming convention because when the module is first imported, the initmodulename () function is called. Every time you implement a C function that Python will call, you have to define two arguments. The first one is called self, and it is a pointer to the called object. The argument self is used when implementing built-in methods to point to the bound object. When a function is implemented, self is set to NULL. The other argument is usually called args, which is a...

The Writer Interface

Interfaces to create writers are dependent on the specific writer class being instantiated. The interfaces described as follows are the required interfaces that all writers must support once initialized. Although most applications can use the AbstractFormatter class as a formatter, the writer must typically be provided by the application. flush() Flushes any buffered output or device control events. new_alignment(align) Sets the alignment style. The align value can be any object, but by...

Tip

PWS is Microsoft's free basic Web server for the Windows 95 platform. You need to pay close attention when using the PWS server because a version of PWS is part of the Front Page Personal Web Server, which doesn't run files from executable directories. Instead, it returns an error message. If you slide your mouse over the PWS icon in the taskbar, and it says Personal Web Server, you have the proper version. Now, let's demonstrate how to configure IIS and PWS for Python CGI scripting. I assume...

Tkinter

As you saw in the previous chapter, other options exist for GUI projects using Python. However, at this moment, Python has chosen to support Tkinter as its official GUI implementation. Tkinter is a standard object-oriented interface to the Tk GUI API, which was originally written by Steen Lumholdt when he was in need for improving his GUI work with Python. In this chapter, you will see how easy it is to subclass Tk widgets using Python's facilities. Some say that it is even easier than when...

Wbmp Module

WBMP is a wireless bitmap format, the graphic format used by WAP mobile phones. A WBMP module for PIL is available for download at http www.rcp.co.uk distributed Downloads The filename is wbmpconvsrc.zip. The download includes a script for converting between WBMP and any other PIL supported bitmap format. OpenGL, created by Silicon Graphics, is a portable library for rendering. It is a complex API with superior performance that became an industry standard for 2D and 3D graphics. The Open GL...

Working with Form Fields and Parsing the Information

The first thing that most beginners in the Web development area want to know is how to get information out of HTML forms and do something with it. The following HTML code results in a Web page (see Figure 12.1) that queries the user about his login information. Note that we use the POST method in the form. Thus, the field values will not be displayed as part of the URL. Figure 12.1. Login Form that calls a CGI script. Figure 12.1. Login Form that calls a CGI script. < HEAD> < TITLE>...

Writing an XML File

As you can see next, it is simple to define your own markup language with XML. The next block of code is the content of a file called survey.xml. This code defines a specific markup language for a given survey. < DOCTYPE SURVEY SYSTEM SURVEY.DTD> < SURVEY> < CLIENT> Lessaworld Corp. Pittsburgh, PA Andre Lessa webmaster lessaworld.com (412)555-5555 < NAME> < LOCATION> < CONTACT> < EMAIL> < TELEPHONE> < SECTION SECTION_ID 1> < QUESTION QUESTION_ID 1...

Extending

Because Python cannot access C C++ functions in a straightforward way, it is necessary to handle the conversion between Python and C C++ data types when putting them to work together. That is when we use the Python extension modules. These extensions work like a thin wrapper of functions written in C C++ that are necessary to bring the C C++ functionality to the developer. It is widely known that interpreted languages execute intensive applications slower than compiled languages. As a result,...

DBM Database Managers Databases

Now, let's look at this other mechanism for storing data. The next modules store data in dbm-style format. This format specifies a simple disk-based storage facility that handles data in a way equivalent to dictionaries. The objects are manipulated by using unique key strings. Each of these modules is an interface to a specific library. dbm, gdbm, and dbhash are database modules that are part of the standard Python distribution. Also included with the standard Python distribution is the anydbm...

Environment Variables

Environment variables are one of the methods that Web servers use to pass information to a CGI script. They are created and assigned appropriate values within the environment that the server produces for the CGI script. The next code generates a list of all environment variables that you have available at the moment, in your browser. import os print Content-type text html n print of Environment print lt BODY gt print s gt s lt BR gt k,v print The following list is the output collected from my...

WxPython

WxPython is a GUI toolkit for the Python programming language that works like a wrapper to the wxWindows C library. It is written in Python and uses the LPGL license. wxPython is a relatively fast cross-platform toolkit, and maybe it hasn't become the standard Python GUI yet because Tkinter is more portable. As a matter of fact, wxPython is the second most common GUI, coming just after Tkinter. Currently only Win32 and UNIX-like systems with GTK are supported. There are plans to support...

The Tkinter Module

Tkinter is Python's de facto standard GUI toolkit. It's the most cross-platform GUI. Many applications are written using Tkinter because it is a very powerful and flexible tool. Maybe the most notable features are its geometry management, which is much better than standard windows, and its efficient Text and Canvas widgets. Many toolkits support as good as or better geometry management some of them are listed in this chapter . Tkinter, which stands for Tk interface, is the standard Python...

Embedding Python in Other Applications

On Windows, Python itself is implemented in a DLL called Python15.dll. Note that the file Python.exe is a small program that calls all the routines stored in the DLL. This is a good example showing that it must be easy to embed Python because it already embeds itself. Besides all this talk about embedding Python in C and C applications, Python can also be embedded Dr. Dietmar Budelsky and Morgan Martinet merged their two separate projects and created The Python for Delphi project. The purpose...

Grail Web Browser

Grail is a free Web browser written entirely in Python, using the Tkinter GUI Tk, which is a free UI toolkit developed by John Ousterhout . Grail has the capability to manipulate SGML, HTML, URL's, images, and sound. Besides, it is easily extended to offer new functionality. Being written in Python helps Grail to have a high adhesion to the Python language. Something similar happens to HotJava, which is a browser written entirely in Java. For documentation and downloads, check out the following...

It executes a given function passing the arguments provided

Basic syntax apply function, tuple of positional arguments , dictionary of keywords arguments gt gt gt apply raise_salary, 6000 , ,employee, ,JohnI, 'id' 13 gt gt gt a b c 10 gt gt gt string.atof s gt gt gt 20 lt x lt 40 gt gt gt x,y,z 5,4,3 gt gt gt a,b b,a Parallel assignment example 2 Note that starting at Python 1.6, the functionality of apply is now available with normal function calling, such as gt gt gt kwargs ,employee, ,John', 'id' 13 gt gt gt raise_salary args, kwargs coerce is used...

ActiveX

An ActiveX control is an OLE control that can live inside an HTML page it can be simple Window objects, such as buttons, text boxes, or scrollbars. It also can be quite complicated, for example, a bar chart graph display can be an ActiveX control. An entire spreadsheet can also be a single control. Each ActiveX control has properties and reacts to external events. Its properties can be modified to change its appearance. For example, its containing program can set color and fonts. External...

Implementing COM Objects in Python

Script Form Edit Delphi

In order to implement COM objects in the Python version of Windows, you need a set of extensions developed by Mark Hammond and Greg Stein. Part of the win32com package, these extensions enable you to do everything that is COM-related, including writing COM clients and COM servers. The following link takes you to the download page of these extensions All the Win32 extensions including the COM extensions are part of the win32all installation package. This package also installs the PythonWin IDE...