Little C Class But Not Too Much

To see how this all works, we need a C++ class. To illustrate, let's code a simple one to be used in Python scripts.171 The following C++ files define a Number class with three methods (add, sub, display), a data member (data), and a constructor and destructor. Example 19-19 shows the header file. 7 For a more direct comparison, you could translate the stack type in Example 19-15 to a C++ class too, but that yields much more C++ code than I care to show in this Python book. Moreover, such a...

Portable Program Launch Framework

With all these different ways to start programs on different platforms, it can be difficult to remember what tools to use in a given situation. Moreover, some of these tools are called in ways that are complicated enough to easily forget (for me, at least). I write scripts that need to launch Python programs often enough that I eventually wrote a module to try and hide most of the underlying details. While I was at it, I made this module smart enough to automatically pick a launch scheme based...

Quick Geometry Lesson

Before I show you PyClock, though, a little background and a confession. Quick -how do you plot points on a circle This, along with time formats and events, turns out to be a core concept in clock widget programs. To draw an analog clock face on a canvas widget, you essentially need to be able to sketch a circle -- the clock face itself is composed of points on a circle, and the second, minute, and hour hands of the clock are really just lines from a circle's center out to a point on the...

Quick Introduction to JPython

Functionally speaking, JPython is a collection of Java classes that run Python code. It consists of a Python compiler, written in Java, that translates Python scripts to Java bytecodes so they can be executed by a Java virtual machine -- the runtime component that executes Java programs and is used by major web browsers. Moreover, JPython automatically exposes all Java class libraries for use in Python scripts. In a nutshell, here's what comes with the JPython system JPython always compiles...

A rand module replaced by random module

The rand module is now deprecated use random instead. A.3.2.9 Assorted Tkinter changes Tkinter became portable to and sprouted native look-and-feel for all major platforms (Windows, X, Macs). There has been a variety of changes in the Tkinter GUI interface The_call__method for StringVar class objects was dropped in Python 1.4 that means you need to explicitly call their get ( ) set( ) methods, instead of calling them with or without arguments. The ScrolledText widget went through a minor...

Regression Test Script

As we've seen, Python provides interfaces to a variety of system services, along with tools for adding others. Example 4-5 shows some commonly used services in action. It implements a simple regression-test system, by running a command-line program with a set of given input files and comparing the output of each run to the prior run's results. This script was adapted from an automated testing system I wrote to catch errors introduced by changes in program source files in a big system, you might...

Simple JPython Example

Once a Python program is compiled with JPython, it is all Java the program is translated to Java bytecodes, it uses Java classes to do its work, and there is no Python left except for the original source code. Because the compiler tool itself is also written in Java, JPython is sometimes called 100 pure Java. That label may be more profound to marketeers than programmers, though, because JPython scripts are still written using standard Python syntax. For instance, Example 15-4 is a legal...

Simple Python File Server Tune in Log on and Drop out

In the last few years, the Internet has virtually exploded onto the mainstream stage. It has rapidly grown from a simple communication device used primarily by academics and researchers into a medium that is now nearly as pervasive as the television and telephone. Social observers have likened the Internet's cultural impact to that of the printing press, and technical observers have suggested that all new software development of interest occurs only on the Internet. Naturally, time will be the...

Add Python Mix Well Repeat

In the last chapter, we explored half of the Python C integration picture -- calling C services from Python. This mode lets programmers speed up operations by moving them to C, and utilize external libraries by wrapping them in C extension modules and types. But the inverse can be just as useful -- calling Python from C. By delegating selected components of an application to embedded Python code, we can open them up to onsite changes without having to ship a system's code. This chapter tells...

Adding Comparison Functions

Since functions can be passed in like any other object, we can easily allow for an optional comparison function. In the next version (Example 17-25), the second argument takes a function that should return true if its first argument should be placed before its second. A lambda is used to provide an ascending-order test by default. This sorter also returns a new sequence that is the same type as the sequence passed in, by applying the slicing techniques used in earlier sections if you sort a...

Adding Relational Algebra to Sets CD

If you are interested in studying additional set-like operations coded in Python, see the following files on this book's CD (see PP2E Dstruct Basic rset.py RSet implementation PP2E Dstruct Basic reltest.py Test script for RSet The RSet subclass defined in rset.py adds basic relational algebra operations for sets of dictionaries. It assumes the items in sets are mappings (rows), with one entry per column (field). RSet inherits all the original Set operations (iteration, intersection, union, &...

Administrative Tools

Now that we have finished implementing a Python-powered, web-enabled, concurrently accessible report database, and published web pages and scripts that make that database accessible to the cyberworld at large, we can sit back and wait for reports to come in. Or almost there still is no way for the site owner to view or delete records offline. Moreover, all records are tagged as not yet verified on submission, and must somehow be verified or rejected. This section lists a handful of tersely...

Alternative encryption schemes

To show how to write alternative encryptors and encoders, secret also includes a digits-string encoder and a character-code shuffling encryptor both are enabled with global flag variables at the top of the module If set to true, the encrypted password is encoded into a string of ASCII code digits separated by dashes. Defaults to false to fall back on URL and HTML escape encoding. If set to false and the encryptor is used on an even-numbered day of the week, the simple character-code encryptor...

Anatomy of a C Extension Type

Although most of file stacktyp.c is missing, there is enough here to illustrate the global structure common to C type implementations The file starts off by defining a C struct called stackobject that will be used to hold per-instance state information -- each generated instance object gets a newly malloc'd copy of the struct. It serves the same function as class instance attribute dictionaries, and contains data that was saved in global variables by the C stack module. As in the module, a set...

And Now for Something Completely Different

This book is about using Python, a very high-level, object-oriented, open source111 programming language, designed to optimize development speed. Although it is completely general-purpose, Python is often called an object-oriented scripting language, partly because of its sheer ease of use, and partly because it is commonly used to orchestrate or glue other software components in an application. 11 Open source systems are sometimes called freeware, in that their source code is freely...

And Now for Something Completely Different Again

The first edition of this book was one of the first to present the Python language. This second edition is an almost completely new advanced Python topics book, designed to be a follow-up to the core language material in Learning Python and supplemented by the reference material in Python Pocket Reference. That is, this edition is focused on ways to use Python, rather than on the language itself. Python development concepts are explored along the way -- in fact, they really become meaningful...

App The root class

The top of the hierarchy knows what it means to be a shell application, but not how to accomplish a particular utility task (those parts are filled in by subclasses). App, listed in Example 4-11, exports commonly used tools in a standard and simplified interface, and a customizable start run stop method protocol that abstracts script execution. It also turns application objects into file-like objects when an application reads itself, for instance, it really reads whatever source its standard...

Appendix A Recent Python Changes

This appendix summarizes prominent changes introduced in Python releases since the first edition of this book. It is divided into three sections, mostly because the sections on 1.6 and 2.0 changes were adapted from release note documents Changes introduced in Python 2.0 (and 2.1) Changes between the first edition and Python 1.5.2 Python 1.3 was the most recent release when the first edition was published (October 1996), and Python 1.6 and 2.0 were released just before this second edition was...

Appendix B Pragmatics

This appendix is a very brief introduction to some install-level details of Python use, and contains a list of Python Internet resources. More information on topics not covered fully here can be found at other resources For additional install details, consult the various README text files in the examples distribution on this book's CD (view CD-ROM content online at http examples.oreilly.com python2), as well as the README files and other documentation that accompany the Python distributions and...

Appendix C Python Versus C

This appendix briefly summarizes some of the differences between Python and C++ classes. Python's class system can be thought of as a subset of C++'s. Although the comparison to Modula 3 may be closer, C++ is the dominant OOP language today. But in Python, things are intentionally simpler -- classes are simply objects with attached attributes that may have links to other class objects. They support generation of multiple instances, customization by attribute inheritance, and operator...

Application Hierarchy Superclasses

This section lists the source code of StreamApp and App -- the classes that do all this extra work on behalf of PackApp and UnpackApp. We don't have space to go through all this code in detail, so be sure to study these listings on your own for more information. It's all straight Python code. I should also point out that the classes listed in this section are just the ones used by the object-oriented mutations of the textpack and textunpack scripts. They represent just one branch of an overall...

Attaching widgets to frames

In larger terms, the critical innovation in this example is its use of frames Frame widgets are just containers for other widgets, and so give rise to the notion of GUIs as widget hierarchies, or trees. Here, win serves as an enclosing window for the other three widgets. In general, though, by attaching widgets to frames, and frames to other frames, we can build up arbitrary GUI layouts. Simply divide the user interface into a set of increasingly smaller rectangles, implement each as a Tkinter...

Automating menu construction

Menus are a powerful Tkinter interface device. If you're like me, though, the examples in this section probably seem like a lot of work. Menu construction can be both code-intensive and error-prone if done by calling Tkinter methods directly. A better approach might automatically build and link up menus from a higher-level description of their contents. In fact, we will -- in Chapter 9, we'll meet a tool called GuiMixin that automates the menu construction process, given a data structure that...

Configuration Settings

The Examples PP2E Config directory on the CD (see http examples.oreilly.com python2) contains example configuration files with comments for Python variable settings. On Windows NT, you can set these variables in the system settings GUI (more on this in a minute) on Windows 98, you can set them from DOS batch files, which can be run from your C autoexec.bat file to make sure they are set every time you start your compute. For example, my autoexec file includes this line which in turn invokes a...

Configuring from a Program

In all cases, sys.path represents the search path to Python scripts and is initialized from path settings in your environment plus standard defaults. This is a normal Python list of strings that may be changed by Python programs to configure the search path dynamically. To extend your search path within Python, do this Because shell variable settings are available to Python programs in the built-in os.environ dictionary, a Python script may also say something like sys.path.append(os.environ...

Python Internet Resources

Finally, Table B-1 lists some of the most useful Internet sites for Python information and resources. Nearly all of these are accessible from Python's home page (http www.python.org) and most are prone to change over time, so be sure to consult Python's home page for up-to-date details. comp.lang.python (python-list cwi.nl) http www.rmi. net lutz about-pp2e.html

Running Python Programs

Python code can be typed at a > > > interactive prompt, run from a C program, or placed in text files and run. There is a variety of ways to run code in files Python files can always be run by typing a command of the form python file.py in your system shell or console box, as long as the Python interpreter program is on your system's search path. On Windows, you can type this command in an MS-DOS console box on Linux, use an xterm. Depending on your platform, you can usually start Python...

Running the Demo Launcher Scripts

The top level of the CD's Examples PP2E package (see http examples.oreilly.com python2) includes Python self-configuring scripts that can be run to launch major book examples, even if you do not configure your environment. That is, they should work even of you don't set your PATH or PYTHONPATH shell variables. These two scripts, PyDemos and PyGadgets, are presented in Chapter 8, and described more fully in both this book's Preface and the CD's README files (see http examples.oreilly.com...

The Book Examples Package

The Examples PP2E CD directory is a Python module package that contains source code files for all examples presented in this book (and more). The PP2E package in turn contains nested module packages that partition the example files into subdirectories by topic. You can either run files straight off the CD, or copy the PP2E directory onto your machine's hard drive (copying over allows you to change the files, and lets Python store their compiled bytecode for faster startups). Either way, the...

Basic Patterns

To illustrate how to combine RE operators, let's start with a few short test files that match simple pattern forms. Comments in Example 18-3 describe the operations exercised check Table 18-1 to see which operators are used in these patterns. Example 18-3. PP2E lang re-basics.py literals, sets, ranges (all print 2 import re pattern, string A.C., xxABCDxx themself matchobj re.search(pattern, string) if matchobj object or None pattobj re.compile(A.*C.*) matchobj pattobj.search(xxABCDxx) obj print...

Binding Events

We met the bind widget method in the last chapter, when we used it to catch button presses in the tutorial. Because bind is commonly used in conjunction with other widgets (e.g., to catch return key presses for input boxes), we're going to make a stop early on the tour here as well. Example 7-15 illustrates more bind event protocols. print 'Widget s X s Y s' (event.widget, event.x, event.y) def showAllEvent(event) print event print attr, ' > ', getattr(event, attr) print 'Got left mouse...

Binding events on specific items

Much like we did for the Text widget, it is also possible to bind events for one or more specific objects drawn on a Canvas with its tag_bind method. This call accepts either a tag name string or object ID in its first argument. For instance, you can register a different callback handler for mouseclicks on every drawn item, or on any in a group of drawn and tagged items, rather than for the entire canvas at large. Example 8-16 binds a double-click handler in both the canvas itself and on two...

Builtin File Objects

For most purposes, the open function is all you need to remember to process files in your scripts. The file object returned by open has methods for reading data (read, readline, readlines), writing data (write, writelines), freeing system resources (close), moving about in the file (seek), forcing data to be transferred out of buffers (flush), fetching the underlying file handle (fileno), and more. Since the built-in file object is so easy to use, though, let's jump right in to a few...

But Its Still Not a Reference Manual

Please note that this edition, like the first, is still more of a tutorial than a reference manual (despite sharing a title pattern with a popular Perl reference text). This book aims to teach, not document. You can use its table of contents and index to track down specifics, and the new structure helps make this easy to do. But this edition is still designed to be used in conjunction with, rather than to replace, Python reference manuals. Because Python's manuals are free, well-written,...

Canvas object tags

But it gets even better In addition to object identifiers, you can also perform canvas operations on entire sets of objects at once, by associating them all with a tag , a name that you make up and apply to objects on the display. Tagging objects in a Canvas is at least similar in spirit to tagging substrings in the Text widget we studied in the prior section. In general terms, canvas operation methods accept either a single object's identifier or a tag name. For example, you can move an entire...

Capturing the stderr Stream

We've been focusing on stdin and stdout redirection, but stderr can be similarly reset to files, pipes, and objects. This is straightforward within a Python script. For instance, assigning sys.stderr to another instance of a class like Output in the preceding example allows your script to intercept text written to standard error too. The popen3 call mentioned previously also allows stderr to be intercepted within a script. Redirecting standard error from a shell command line is a bit more...

CGI Script Tradeoffs

As shown in this chapter, PyMailCgi is still something of a system in the making, but it does work as advertised by pointing a browser at the main page's URL, I can check and send email from anywhere I happen to be, as long as I can find a machine with a web browser. In fact, any machine and browser will do Python doesn't even have to be installed.151 That's not the case with the PyMailGui client-side program we wrote in Chapter 11. 5 This property can be especially useful when visiting...

Checkbutton Radiobutton and Scale

This section introduces three widget types -- the Checkbutton (a multiple-choice input widget), the Radionbutton (a single-choice device), and the Scale (sometimes known as a slider). All are variations on a theme, and somewhat related to simple buttons, so we'll explore them as a group here. To make these widgets more fun to play with, we'll reuse the dialogTable module shown in Example 7-8 to provide callbacks for widget selections (callbacks pop up dialog boxes). Along the way, we'll also...

Checkbuttons and variables

When I first studied this widget, my initial reaction was So why do we need Tkinter variables here at all when we can register button-press callbacks Linked variables may seem superfluous at first glance, but they simplify some GUI chores. Rather than asking you to accept this blindly, though, let me explain why. Keep in mind that a checkbuttons's command callback will be run on every press -whether the press toggles the checkbutton to a selected or deselected state. Because of that, if you...

Checking for Missing and Invalid Inputs

So far, we've been triggering the CGI script by selecting a language name from the pull-down list in the main HTML page. In this context, we can be fairly sure that the script will receive valid inputs. Notice, though, that there is nothing to prevent a user from passing the requested language name at the end of the CGI script's URL as an explicit parameter, instead of using the HTML page form. For instance, a URL of the form yields the same Python response page shown in Fj ure_12-.2Q.iim...

Client socket calls

On the other hand, client programs like the one shown in Example 10-2 follow simpler call sequences. The main thing to keep in mind is that the client and server must specify the same port number when opening their sockets, and the client must identify the machine on which the server is running (in our scripts, server and client agree to use port number 50007 for their conversation, outside the standard protocol range) sockobj socket(AF_INET, SOCK_STREAM) Creates a Python socket object in the...

Coding for reusability

A postscript I coded all the demo launcher bars deployed by the last three examples to demonstrate all the different ways that their widgets can be used. They were not developed with general-purpose reusability in mind in fact, they're not really useful outside the context of introducing widgets in this book. That was by design most Tkinter widgets are easy to use once you learn their interfaces, and Tkinter already provides lots of configuration flexibility by itself. But if I had in mind to...

Commercially Published References

At the risk of sounding like a marketing droid, I should mention that you can also purchase the Python manual set, printed and bound see the book information page at http www.python.org for details and links. Commercially published Python reference books are also available today, including Python Essential Reference (New Riders Publishing) and Python Pocket Reference (O'Reilly). The former is more complete and comes with examples, but the latter serves as a convenient memory-jogger once you've...

Common conversion codes

With a few exceptions, PyArg_Parse(Tupie) and Py_BuiidVaiue use the same conversion codes in format strings. A list of all supported conversion codes appears in Python's extension manuals. The most commonly used are shown in Table 19-1 the tuple, list, and dictionary formats can be nested. These codes are mostly what you'd expect (e.g., i maps between a C int and a Python integer object), but here are a few usage notes on this table's entries Pass in the address of a char* for s codes when...

Common input devices alternative layout

Ult wm taw flcnpt, '-.-j. ill.lut afju'. ot Lit mci iLtli Nulid Lilt sipormiM f li f-1 int rferf an jr-ic-tame lege h(ne. th r Cj iCf -T ' M'.iii-in ltiif - f tic n- d o i .** rzjct wit* lie u.-er cLejit iiniphiflf lilt- r.illtm inn Ciiltti mini I ii< k .SlilirniE iiniphiflf lilt- r.illtm inn Ciiltti mini I ii< k .SlilirniE ------Kfti-i-in -H's 'y-Ai . * Now, before you go blind trying to detect the differences in this and the prior HTML file, I should note that the HTML differences that...

Common Utilities Module

The file commonhtml.py, shown in Example 13-14, is the Grand Central Station of this application -- its code is used and reused by just about every other file in the system. Most of it is self-explanatory, and I've already said most of what I wanted to say about it earlier, in conjunction with the CGI scripts that use it. I haven't talked about its debugging support, though. Notice that this module assigns sys.stderr to sys.stdout, in an attempt to force the text of Python error messages to...

Compiled pattern objects

At the next level, pattern objects provide similar attributes, but the pattern string is implied. The re.compile function in the previous section is useful to optimize patterns that may be matched more than once (compiled patterns match faster). Pattern objects returned by re.compile have these sorts of attributes match(string , pos , endpos ) search(string , pos , endpos ) split(string 1, maxsplit1) sub(repl, string , count ) subn(repl, string , count ) Same as the re functions, but the...

Compiling and Running

This C extension file is compiled and dynamically or statically linked like previous examples file makefile.stack on the CD (see http examples.oreilly.com python2) handles the build like this gcc stacktyp.c -g -I (PY) Include -I (PY) -fpic -shared -o stacktype.so Once compiled, you can import the C module and make and use instances of the C type it defines much as if it were a Python class (but without inheritance). You would normally do this from a Python script, but the interactive prompt is...

Complete Program Examples

The rest of this chapter presents a handful of complete GUI programs, as examples of how far Python and Tkinter can take you. Because I've already shown the interfaces these scripts employ, this section is mostly screen shots, program listings, and a few bullets describing some of the most important aspects of these programs. In other words, this is a self-study section read the source, run the examples on your own computer, and refer to the previous chapters for further details on the code...

Converting strings in CGI scripts

Just for fun, the script echoes back the name of the server platform by fetching sys.platform along with the square of the age input field. Notice that the age input's value must be converted to an integer with the built-in int function in the CGI world, all inputs arrive as strings. We could also convert to an integer with the built-in string.atoi or eval function. Conversion (and other) errors are trapped gracefully in a try statement to yield an error line, rather than letting our script...

CPPEpython Launch Browserpy live lutz starshippythonnet

Opening http starship.python.net lutz Starting In Chapter 8, we'll see that this script is also run to start Internet examples in the top-level demo launcher system the PyDemos script presented in that chapter portably opens local or remote web page files with this button-press callback pagepath os.getcwd( ) + ' Internet Cgi-Web' demoButton('PyErrata', 'Internet-based errata report system', 'LaunchBrowser.py -file s PyErrata pyerrata.html' pagepath) site 'starship.python.net lutz'...

Crossprogram communication

Spawning GUIs as programs is the ultimate in code independence, but makes the lines of communication between components more complex. For instance, because the demos run as programs here, there is no easy way to run all their report methods from the launching script's window pictured in the middle of Figure 7-34. In fact, the States button is gone this time, and we only get PortableLauncher messages in stdout as the demos start up C PP2E Gui Tour> python demoAll_prg.py On some platforms,...

Ctempfc B pyexe mypyexe

Comparing files py152.exe and mypy152.exe FC no differences encountered Finally, the splitter is also smart enough to create the output directory if it doesn't yet exist, or clear out any old files there if it does exist. Because the joiner combines whatever files exist in the output directory, this is a nice ergonomic touch -- if the output directory was not cleared before each split, it would be too easy to forget that a prior run's files are still there. Given that my kids are running these...

CWD and Command Lines

This distinction between the CWD and import search paths explains why many scripts in this book designed to operate in the current working directory (instead of one whose name is passed in) are run with command lines like this C temp> python X PyTools cleanpyc-py.py In this example, the Python script file itself lives in the directory C PP2ndEd examples PP2E PyTools, but because it is run from C temp, it processes the files located in C temp (i.e., in the CWD, not in the script's home...

CWD Files and Import Paths

When you run a Python script by typing a shell command line like python dir1 dir2 file.py, the CWD is the directory you were in when you typed this command, not dir1 dir2. On the other hand, Python automatically adds the identity of the script's home directory to the front of the module search path, such that file.py can always import other files in dir1 dir2, no matter where it is run from. To illustrate, let's write a simple script to echo both its CWD and module search path whereami.py...

Data Structures Versus Python Builtins

Now that I've shown you all these complicated algorithms, I need to also tell you that at least in some cases, they may not be an optimal approach. Built-in types like lists and dictionaries are often a simpler and more efficient way to represent data. For instance These may be useful in many applications, but Python dictionaries already provide a highly optimized, C-coded, search table tool. Indexing a dictionary by key is likely to be faster than searching a Python-coded tree structure >...

Debugging CGI scripts

Errors happen, even in the brave new world of the Internet. Generally speaking, debugging CGI scripts can be much more difficult than debugging programs that run on your local machine. Not only do errors occur on a remote machine, but scripts generally won't run without the context implied by the CGI model. The script in Example 12-11 demonstrates the following two common debugging tricks. This script assigns sys.stderr to sys.stdout so that Python error messages wind up being displayed in the...

Decoding base data

Mail messages and attachments are frequently sent in an encoding format such as uu or base64 binary data files in particular must be encoded in a textual format for transit using one of these encoding schemes. On the receiving end, such encoded data must first be decoded before it can be viewed, opened, or otherwise used. The Python program in Example 11-19 knows how to perform base64 decoding on data stored in a file. Example 11-19. PP2E Internet Email...

Decoding Mail Message Attachments

In the last section, we learned how to parse out email message headers and bodies with the rfc822 and StringIO modules. This isn't quite enough for some messages, though. In this section, I will introduce tools that go further, to handle complex information in the bodies of email messages. One of the drawbacks of stubbornly clinging to a Telnet command-line email interface is that people sometimes send email with all sorts of attached information -- pictures, MS Word files, uuencoded tar files,...

Designing for Reuse and Growth

I admit it PyErrata may be thrifty, but it's also a bit self-centered. The database interfaces presented in the prior sections work as planned and serve to separate all database processing from CGI scripting details. But as shown in this book, these interfaces aren't as generally reusable as they could be moreover, they are not yet designed to scale up to larger database applications. Let's wrap up this chapter by donning our software code review hats for just a few moments and exploring some...

Downloading Web Sites Mirrors

Once upon a time, Telnet was all I needed. My web site lived at an Internet Service Provider (ISP) that provided general and free Telnet access for all its customers. It was a simple time. All of my site's files lived only in one place -- at my account directory on my ISP's server machine. To make changes to web pages, I simply started a Telnet session connected to my ISP's machine and edited my web pages there online. Moreover, because Telnet sessions can be run from almost any machine with an...

Endofline translations on Windows

Strictly speaking, on some platforms you may not need the b at the end of the open mode argument to process binary files the b is simply ignored, so modes r and w work just as well. In fact, the b in mode flag strings is usually only required for binary files on Windows. To understand why, though, you need to know how lines are terminated in text files. For historical reasons, the end of a line of text in a file is represented by different characters on different platforms it's a single n...

Escaping HTML Code

As we saw earlier, cgi.escape translates code for inclusion within HTML. We normally call this utility from a CGI script, but it's just as easy to explore its behavior interactively > > > cgi.escape('a < b > c & d spam', 1) 'a & lt b & gt c & amp d & quot spam& quot ' > > > s cgi.escape(1< 2 < b> hello< b> ) '1& lt 2 Python's cgi module automatically converts characters that are special in HTML syntax according to the HTML convention. It translates...

Escaping mail text and passwords in HTML

Notice that everything you see on the message view page in Figure 13-13 is escaped with cgi.escape. Header fields and the text of the mail itself might contain characters that are special to HTML and must be translated as usual. For instance, because some mailers allow you to send messages in HTML format, it's possible that an email's text could contain a < textarea> tag, which would throw the reply page hopelessly out of sync if not escaped. One subtlety here HTML escapes are important...

Escaping URLs

By contrast, URLs reserve other characters as special and must adhere to different escape conventions. Because of that, we use different Python library tools to escape URLs for transmission. Python's urllib module provides two tools that do the translation work for us quote, which implements the standard xx hexadecimal URL escape code sequences for most nonalphanumeric characters, and quote_plus, which additionally translates spaces to + plus signs. The urllib module also provides functions for...

Escaping URLs Embedded in HTML Code

But what do we do for URLs inside HTML That is, how do we escape when we generate and embed text inside a URL, which is itself embedded inside generated HTML code Some of our earlier examples used hardcoded URLs with appended input parameters inside < a href> hyperlink tags file languages2.cgi, for instance, prints HTML that includes a URL < a Because the URL here is embedded in HTML, it must minimally be escaped according to HTML conventions (e.g., any < characters must become & lt...

Evaluating expressions with stacks

Now that you have the general idea of what PyCalc does, I need to say a little bit about how it does what it does. Most of the changes in this version involve managing the expression display and evaluating expressions. PyCalc is structured as two classes The caicGui class manages the GUI itself. It controls input events and is in charge of the main window's display field at the top. It doesn't evaluate expressions, though for that, it sends operators and operands entered in the GUI to an...

Example PPEDbaseguitoolspy

added extras for entry width, calcgui font color def frame(root, side, **extras) widget Frame(root) widget.pack(side side, expand YES, fill BOTH) if extras apply(widget.config, ( ), extras) return widget def label(root, side, text, **extras) widget Label(root, text text, relief RIDGE) widget.pack(side side, expand YES, fill BOTH) if extras apply(widget.config, ( ), extras) return widget def button(root, side, text, command, **extras) widget Button(root, text text, command command)...

Example PPEDbasetestdatapy

definitions for testing shelves, dbm, and formgui cast definitions for testing shelves, dbm, and formgui cast def init (self, name ( ), job '') no need for arg def init (self, name ( ), job '') no need for arg self.job job def setattr (self, attr, value) print 'validation error kids ', if attr 'name' and type(value) t print 'validation error name type self.__dict__ attr value The cast object here is intended to represent a table of records (it's really a dictionary of dictionaries when written...

Example PPEDstruct Basicstackpy

For x in start self.push(x) self.reverse( ) self.stack obj + self.stack def pop(self) if not self.stack raise error, 'underflow' top, self.stack self.stack 0 , self.stack 1 return top def top(self) if not self.stack raise error, 'underflow' return self.stack 0 def empty(self) return ' Stack s ' self.stack backquotes, return Stack(self.stack + other.stack) instance2 return Stack(self.stack * reps) def getitem (self, offset) return self.stack offset return Stack(self.stack low high ) def getattr...

Example PPEDstruct Classicsbtreekeyspy

Def init (self) self.tree EmptyNode( ) def repr (self) def lookup(self, key) def insert(self, key, val) self.tree self.tree.insert(key, val) return '*' def lookup(self, key) bottom return None def insert(self, key, val) return BinaryNode(self, key, val, self) def init (self, left, key, val, right) self.key, self.val key, val self.left, self.right left, right def lookup(self, key) if self.key key return self.val elif self.key > key def insert(self, key, val) if self.key key self.val val elif...

Example PPEDstruct Classicsgsearchpy

find all paths from start to goal in graph def search(start, goal, graph) solns generate( start , goal, solns, graph) solns.sort( lambda x, y cmp(len(x), len length def generate(path, goal, solns, graph) state path -1 if state goal if name ' main ' import gtestfunc gtestfunc.tests(search) The second searcher, in Example 17-17, uses an explicit stack of paths to be expanded using the tuple-tree stack representation we explored earlier in this chapter.

Example PPEDstruct Classicsgtestobjpy

S.arcs P, M P.arcs S, M, A A.arcs M print S.search(M) This test finds three paths in its graph between nodes S and M. If you'd like to see more Python graph code, check out the files in directory MoreGraphs on the CD (see http examples.oreilly.com python2). These are roughly the same as the ones listed here, but add user interaction as each solution is found. In addition, we've really only scratched the surface of this domain here see other books for additional topics (e.g., breadth- and...

Example PPEDstruct Classicspermcombpy

If size 0 or not list matters here for i in range(len(list)) pick list i i+1 for x in subset(rest, size-1) result.append(pick + x) return result if size 0 or not list doesn't matter for i in range(0, (len(list) - size) pick list i i+1 rest list i+1 for x in combo(rest, size - 1) result.append(pick + x) return result As in the reversal functions, all three of these work on any sequence object that supports len, slicing, and concatenation operations. For instance, we can use permute on instances...

Example PPEDstruct Classicsrevpy

If not list empty (not always ) return list the same sequence type return reverse(list 1 ) + list 1 add front item on the def ireverse(list) res list 0 for i in range(len(list)) These functions work on any sequence, and return a new sequence of the same type as the sequence passed in. If we pass in a string, we get a new string as the result. In fact, they reverse any sequence object that responds to slicing, concatenation, and len -- even instances of Python classes and C types. In other...

Example PPEDstruct Classicssortpy

Def sort(seq, func (lambda x,y x < y)) default res res i + seq j j+1 + res i seq can be table ( 'name' 'doe' , 'name' 'john' ) print sort(list(table), (lambda x, y x 'name' > y 'name' )) print sort(tuple(table), (lambda x, y x 'name' < y 'name' )) This time, the table entries are ordered per a field comparison function passed in sort2.py 'name' 'john' , 'name' 'doe' ( 'name' 'doe' , 'name' 'john' ) abcxyz This version also dispenses with the notion of a field altogether and lets the...

Example PPEDstruct TreeViewtreeviewpy

wrappers for viewing tree types in the book, plus test cases gui from treeview wrappers import TreeWrapper, TreeViewer from PP2E.Dstruct.Classics import btree from PP2E.Lang.Parser import parser2 binary tree wrapper class BinaryTreeWrapper(TreeWrapper) embed binary tree in def children(self, node) adds viewer protocols return None def label(self, node) try return str(node) def onInputLine(self, line, viewer) t btree.BinaryTree( ) for x in items t.insert(x) binary tree extension class...

Example PPEGui Clockclockpy

PyClock a clock GUI, with both analog and digital display modes, a popup date label, clock face images, resizing, etc. May be run both stand-alone, or embbeded (attached) in other GUIs that need a clock. from Tkinter import * import math, time, string Option configuration classes defaults--override in instance or subclass size 200 hh, mh, sh, cog 'black', 'navy', 'blue', 'red' center class PhotoClockConfig(ClockConfig) sample configuration size 320 bg, hh, mh 'white', 'blue', 'orange' Digital...

Example PPEGui ClockplotterGuipy

plot circles (like I did in high school) import math, sys from Tkinter import * angle tick * (360.0 range) radiansPerDegree math.pi 180 pointX int( round( radius * math.sin(angle * radiansPerDegree) )) pointY int( round( radius * math.cos(angle * radiansPerDegree) )) return (pointX, pointY) def circle(points, radius, centerX, centerY, slow 0) canvas.delete('lines') canvas.delete('points') for i in range(points) x, y point(i+1, points, radius-4) scaledX, scaledY (x + centerX), (centerY - y)...

Example PPEGui Introguibpy

From gui7 import HelloPackage or get from gui7c-- Label(frm, text 'hello').pack() part HelloPackage(frm) part.pack(side RIGHT) fails --need This won't quite work, because part isn't really a widget. To treat it as such, you must descend to part.top before making GUI configurations, and hope that the name top never changes. The class could make this better by defining a method that always routes unknown attribute fetches to the embedded Frame, as in Example 6-26.

Example PPEGui Introguidpy

From Tkinter import * from gui6 import Hello def make_widgets(self) extend Hello.make_widgets(self) Button(self, text 'Extend', command self.quit).pack(side RIGHT) def message(self) This subclass's make_widgets method here first builds the superclass's widgets, then adds a second Extend button on the right, as shown in Figure 6-24.

Example PPEGui ShellGuipackdlgpy

added file select dialogs, empties test could use grids from glob import glob filename from Tkinter import * gui widget from tkFileDialog import * file selector from PP2E.System.App.Clients.packapp import PackApp use pack s1, s2 StringVar(), StringVar( ) function output, patterns s1.get(), s2.get( ) destroy if output and patterns patterns string.split(patterns) filenames for sublist in map(glob, patterns) filenames filenames + sublist run class like a pop-up dialog sets app PackApp(ofile...

Example PPEGui TextEditorsimpleshellpy

Line raw input('> > > ') single line statements only exec line in namespace or eval( ) and print result Depending on the user's preference, PyEdit either does something similar to this to run code fetched from the text widget, or uses the launchmodes module we wrote at the end of Chapter 3 to run the code's file as an independent program. There are a variety of options in both schemes that you can customize as you like (this is Python, after all). See the onRunCode method for details, or...

Example PPEGui TextEditortext Editorpy

PyEdit 1.1 a Python Tkinter text file editor and component. Uses the Tk text widget, plus GuiMaker menus and toolbar buttons to implement a full-featured text editor that can be run as a stand-alone program, and attached as a component to other GUIs. Also used by PyMail and PyView to edit mail and image file notes. from PP2E.Gui.Tools.guimaker import * SEL_FIRST SEL + '.first' SEL_LAST SEL + '.last' import sys, os, string FontScale 0 9+FontScale, l2+FontScale, lO+FontScale, lO+FontScale,...

Example PPEGui Toolsguimakerpy

An extended Frame that makes window menus and tool-bars automatically. Use GuiMakerFrameMenu for embedded components (makes frame-based menus). Use GuiMakerWindowMenu for top-level windows (makes Tk8.0 window menus). See the self-test code (and PyEdit) for an example layout tree format. from Tkinter import * from types import * class GuiMaker(Frame) menuBar toolBar subclasses def init (self, parent None) Frame. init (self, parent) self.pack(expand YES, fill BOTH) stretchable make menu bar at...

Example PPEGui Toolsguimixinpy

a mixin class for other frames common methods for canned-dialogs, spawning programs, etc must be mixed with a class derived from Frame for its quit method from ScrolledText import ScrolledText from PP2E.launchmodes import PortableLauncher, System def infobox(self, title, text, *args) dialogs return showinfo(title, text) bkwd compat def question(self, title, text, *args) return askyesno(title, text) showerror('Not implemented', 'Option not available') def quit(self) ans self.question('Verify...

Example PPEGui ToolsReloadactionspy

callback handlers reloaded each time triggered print 'spamSpamSPAM' could build a dialog self.method1( ) access the 'Hello' instance Try running rad and editing the messages printed by actions in another window you should see your new messages printed in the stdout console window each time the GUI's buttons are pressed. This example is deliberately simple to illustrate the concept, but the actions reloaded like this in practice might build pop-up dialogs, new top-level windows, and so on....

Example PPEGui ToolsReloadradpy

Import actions get initial callback handlers def init (self, master None) Frame. init (self, master) self.pack( ) self.make widgets( ) Button(self, text 'message1', Button(self, text 'message2', reload(actions) need to reload actions module before actions.message1( ) now new version triggered by print 'exposed method ' called from actions function When run, this script makes a two-button window that triggers the message1 and message2 methods. Example 9-12 contains the actual callback handlers'...

Example PPEGui Touralarmhidepy

Class Alarm(alarm.Alarm) change alarm def init (self, msecs 1000) self.shown 0 self.after(self.msecs, self.repeater) def init (self, msecs 1000) self.shown 0 self.after(self.msecs, self.repeater) When this script is run, the same window appears, but the button is erased or redrawn on alternating timer events. The widget pack_forget method erases (unmaps) a drawn widget, and pack makes it show up again grid_forget and grid similarly hide and show widgets in a grid. The pack_forget method is...

Example PPEGui Touralarmpy

usr local bin python from Tkinter import * def repeater(self) self.bell() self.stopper.flash() self.after(self.msecs, self.repeater) def init (self, msecs 1000) Frame. init (self) self.msecs msecs self.pack() stopper Button(self, text 'Stop the beeps ', command self.quit) stopper.config(bg 'navy', fg 'white', bd 8) This script builds the window in Figure 8-37 and periodically calls both the button widget's flash method to make the button flash momentarily (it alternates colors quickly), and...

Example PPEGui Touralarmwithdrawpy

If self.master.state() 'normal' displayed self.after(self.msecs, self.repeater) if name ' main ' Alarm().mainloop() root This works the same, but the entire window appears or disappears on beeps -- you have to press it when it's shown. There are lots of other effects you could add to the alarm. Whether your buttons and windows should flash and disappear or not, though, probably depends less on Tkinter technology than on your users' patience.

Example PPEGui Tourbuttonpicsfuncpy

From Tkinter import * from glob import glob import demoCheck import random gifdir ' gifs ' attach checkbutton demo to me lbl Label(root, text none, bg 'blue', fg 'red') pix Button(root, text Press me, command draw, bg 'white') demoCheck.Demo(root, relief SUNKEN, bd 2).pack(fill BOTH) files glob(gifdir + *.gif) now images map(lambda x (x, PhotoImage(file x)), files) hold This code uses a handful of built-in tools from the Python library The Python glob module we met earlier in the book gives a...

Example PPEGui Tourbuttonpicspy

From Tkinter import * from glob import glob import demoCheck import random gifdir ' gifs ' attach checkbox example to me default dir to load gif files def init (self, gifdir gifdir, parent None) Frame. init (self, parent) self.pack() self.lbl Label(self, text none, bg 'blue', fg 'red') self.pix Button(self, text Press me, command self.draw, bg 'white') self.lbl.pack(fill BOTH) self.pix.pack(pady 10) demoCheck.Demo(self, relief SUNKEN, bd 2).pack(fill BOTH) files glob(gifdir + *.gif) self.images...

Example PPEGui Tourcanvasbindpy

Print 'Got canvas click', event.x, event.y, event.widget def onObjectClick(event) print 'Got object click', event.x, event.y, event.widget, print event.widget.find closest(event.x, event.y) find text object's id canv Canvas(root, width 100, height 100) obj1 canv.create text(50, 30, text 'Click me one') obj2 canv.create text(50, 70, text 'Click me two') canv.bind('< Double-1> ', onCanvasClick) canvas canv.tag bind(obj1, '< Double-1> ', onObjectClick) item canv.tag bind(obj2, '<...

Example PPEGui TourcanvasDrawpy

draw elastic shapes on a canvas on drag, move on right click see canvasDraw tags*.py for extensions with tags and animation canvas Canvas(width 300, height 300, bg 'beige') canvas.pack() canvas.bind('< ButtonPress-1> ', self.onStart) click and drag event x,y when scrolled to bottom of canvas canvas x,y -y differs radically when scrolled to a mid point in the canvas delete all canvas.bind('< ButtonPress-3> ', self.onMove) move latest self.canvas canvas self.drawn None self.kinds...

Example PPEGui TourcanvasDrawtagspy

add tagged moves with time.sleep (not widget.after or threads) time.sleep does not block the gui event loop while pausing, but screen not redrawn until callback returns or widget.update call the currently running onMove callback gets exclusive attention until it returns others pause if press 'r' or 'o' during move from Tkinter import * import canvasDraw, time class def init (self, parent None) canvasDraw.CanvasEventsDemo. init (self, parent) self.canvas.create text(75, 8, text 'Press o and r...

Example PPEGui TourcanvasDrawtagsthreadpy

similar, but run time.sleep loops in parallel with threads, not .after events or single active time.sleep loop because threads run in parallel, this also allows ovals and rectangles to be moving at the same time and does not require update calls to refresh the gui in fact, calling .update() can make this crash today, though some canvas calls seem to be thread safe or else this wouldn't work at all from Tkinter import * import canvasDraw tags import thread, time class...

Example PPEGui Tourconfigbuttonpy

Widget Button(text 'Spam', padx 10, pady 10) widget.pack(padx 2 0, pady 20) widget.config(cursor 'gumby') widget.config(bd 8, relief RAISED) widget.config(bg 'dark green', fg 'white') widget.config(font (,helvetica', 20, 'underline italic')) mainloop() To see the effects generated by these two script's settings, try out a few changes on your computer. Most widgets can be given a custom appearance in the same way, and we'll see such options used repeatedly in this text. We'll also meet...

Example PPEGui Tourconfiglabelpy

Labelfont ('times', 20, 'bold') style widget Label(root, text 'Hello config world') widget.config(bg 'black', fg 'yellow') black label widget.config(height 3, width 20) initial size widget.pack(expand YES, fill BOTH) root.mainloop() Remember, we can call a widget's config method to reset its options at any time, instead of passing them all to the object's constructor. Here, we use it to set options that produce the window in Figure 7-1. Figure 7-1. A custom label appearance Figure 7-1. A custom...

Example PPEGui TourdemoAllfrmpy

4 demo class components (subframes) on one window there are 5 Quitter buttons on this one window too guis can be reused as frames, windows, processes from Tkinter import * from quitter import Quitter demoModules 'demoDlg', 'demoCheck', 'demoRadio', 'demoScale' parts part.config(bd 2, relief GROOVE) part.pack(side LEFT, fill BOTH) parts.append(part) for part in parts run demo report print part. module + ' ', if hasattr(part, 'report') Label(root, text 'Multiple Frame demo', bg 'white').pack()...