File Pattern Search Utility

The next script searches for patterns in a set of files, much like the grep command-line program. We wrote file and directory searchers earlier, in Chapter 5. Here, the file searches look for patterns instead of simple strings (see Example 18-8). The patterns are typed interactively separated by a space, and the files to be searched are specified by an input pattern for Python's glob.glob filename expansion tool we studied earlier, too. usr local bin python import sys, re, glob from string...

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...

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...

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...

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...

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...

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...

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...

Changing serverside examples

Of course, running scripts in your browser isn't quite the same as writing scripts on your own. If you do decide to change these CGI programs or write new ones from scratch, you must be able to access web server machines To change server-side scripts, you need an account on a web server machine with an installed version of Python. A basic account on such a server is often enough. Then edit scripts on your machine and upload to the server by FTP. To type explicit command lines on a server...

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...

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...

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'...

CPPESystem Filetoolspython listerwalkpy CTemp

The walk paradigm also allows functions to tailor the set of directories visited by changing the file list argument in place. The library manual documents this further, but it's probably more instructive to simply know what walk truly looks like. Here is its actual Python-coded implementation for Windows platforms, with comments added to help demystify its operation def walk(top, func, arg) current dirname try names os.listdir(top) file dir names here except os.error path prefix return...

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...

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...

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...

Displaying Arbitrary Server Files on the Client

Almost immediately after writing the languages source code viewer script in the previous example, it occurred to me that it wouldn't be much more work, and would be much more useful, to write a generic version -- one that could use a passed-in filename to display any file on the site. It's a straightforward mutation on the server side we merely need to allow a filename to be passed in as an input. The getfile.cgi Python script in Example 12-24 implements this generalization. It assumes the...

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 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 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 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 Introguicpy

Self.pack() self.makeWidgets() def makeWidgets(self) Hello(self).pack(side RIGHT) attach a Hello Button(self, text 'Attach', command self.quit).pack(side LEFT) if _name_ '_main_' HelloContainer().mainloop() This looks and works exactly like gui6b, but registers the added button's callback handler as self.quit, which is just the standard quit widget method this class inherits from Frame. The window this time represents two Python classes at work -the embedded component's widgets on the right...

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 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 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 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()...

Example PPEGui TourdemoDlgpy

From Tkinter import * get base widget set from dialogTable import demos button callback handlers from quitter import Quitter attach a quit object to me def init (self, parent None) Frame.__init__(self, parent) self.pack() Label(self, text Basic demos).pack() for (key, value) in demos.items() Button(self, text key, command value).pack(side TOP, Quitter(self).pack(side TOP, fill BOTH) if name ' main ' Demo().mainloop() This script creates the window shown in Figure 7-11 when run as a standalone...

Example PPEGui Tourdlgcustompy

From Tkinter import * makemodal (len(sys.argv) > 1) Label(win, text 'Hard drive reformatted ').pack() add a few widgets Button(win, text 'OK', command win.destroy).pack() set destroy callback win.focus set() take over input focus, win.grab set() disable other windows while I'm win.wait window() and wait here until win destroyed print 'dialog exit' else returns right away Button(root, text 'popup', command dialog).pack() root.mainloop() This script is set up to create a pop-up dialog window in...

Example PPEGui Tourdlgoldpy

From Tkinter import * from Dialog import Dialog def init (self, master None) Frame. init (self, master) Pack.config(self) same as self.pack() Button(self, text 'Pop1', command self.dialog1).pack() Button(self, text 'Pop2', command self.dialog2).pack() def dialog1(self) text 'An example of a popup-dialog ' 'box, using older Dialog.py.', bitmap 'questhead', default 0, strings ('Yes', 'No', 'Cancel')) if ans.num 0 self.dialog2() def dialog2(self) text I'm afraid I can't let you do that, default 0,...

Example PPEGui Tourentrymodalpy

must fetch before destroy with entries from Tkinter import * from entry2 import makeform, fetch, fields fetch(entries) must fetch before window popup.destroy() fails with msgs if stmt order is popup Toplevel() show form in modal dialog window Button(popup, text 'OK', command (lambda e ents show(e)) ).pack() popup.grab set() popup.focus set() popup.wait window() wait for destroy here Button(root, text 'Dialog', command ask).pack() root.mainloop() When run, pressing the button in this program's...

Example PPEGui Tourentrypy

use StringVar variables and layout by columns def makeform(root, fields) form Frame(root) left Frame(form) rite Frame(form) form.pack(fill X) left.pack(side LEFT) rite.pack(side RIGHT, expand YES, lab Label(left, width 5, text field) ent Entry(rite) lab.pack(side TOP) ent.pack(side TOP, fill X) var StringVar() ent.config(textvariable var) var.set('enter here') variables.append(var) return variables if __name__ '__main__' Toot Tk() vars makeform(root, fields) Button(root, text 'Fetch', command...

Example PPEGui TourGridgridpy

Label(root, text 'Grid').grid(columnspan 2) r 1 l Label(root, text c, relief RIDGE, width 25) e Entry(root, bg c, relief SUNKEN, width 50) l.grid(row r, column 0, sticky NSEW) e.grid(row r, column 1, sticky NSEW) root.rowconfigure(r, weight 1) root.columnconfigure(0, weight 1) root.columnconfigure(1, weight 1) Label(root, text 'Pack').pack() for c in colors l Label(f, text c, relief RIDGE, width 25) e Entry(f, bg c, relief SUNKEN, width 50) f.pack(side TOP, expand YES, fill BOTH) l.pack(side...

Example PPEGui TourimgCanvaspy

Gifdir gifs from sys import argv from Tkinter import * filename (len(argv) > 1 and argv 1 ) or 'ora-lp.gif' name on img PhotoImage(file gifdir+filename) can Canvas(win) can.pack(fill BOTH) can.config(width img.width(), height img.height()) size to img can.create image(2, 2, image img, anchor NW) win.mainloop() Figure 7-38. Sizing the canvas to match the photo Figure 7-38. Sizing the canvas to match the photo And that's all there is to it. In Chapter 8, well see images show up in a Menu, other...

Example PPEGui Tourmbuttonpy

Menu(mbutton) config(menu picks) picks.add command(label 'spam', picks.add command(label 'eggs', picks.add command(label 'bacon', mbutton.pack() mbutton.config(bg 'white,, bd 4, root.mainloop() command root.quit) command root.quit) command root.quit) Figure 8-8. A Menubutton all by itself Figure 8-8. A Menubutton all by itself The related Tkinter Optionmenu widget displays an item selected from a pull-down menu. It's roughly like a Menubutton plus a display label, and displays a menu of...

Example PPEGui Tourmenuwinmultipy

From menu win import makemenu from Tkinter import * for i in range(3) 3 popup windows with menus Label(win, bg 'black', height 5, width 15).pack(expand YES, fill BOTH) Button(root, text Bye, command root.quit).pack() root.mainloop() Figure 8-3. A File tear-off and Edit cascade Figure 8-3. A File tear-off and Edit cascade Figure 8-4. Multiple Toplevels with menus Figure 8-4. Multiple Toplevels with menus

Example PPEGui Touroptionmenupy

From Tkinter import * root Tk() varl StringVar() var2 StringVar() optl OptionMenu(root, varl, 'spam', 'eggs', 'toast') like opt2 OptionMenu(root, var2, 'ham', 'bacon', 'sausage') but shows choice opt1.pack(fill X) opt2.pack(fill X) varl.set('spam') var2.set('ham') def state() print var1.get(), var2.get() linked Button(root, command state, text 'state').pack() root.mainloop() There are other menu-related topics that we'll skip here in the interest of space. For instance, scripts can add entries...

Example PPEGui Tourquitterpy

a quit button that verifies exit requests to reuse, attach an instance to other guis from tkMessageBox import askokcancel def init (self, parent None) Frame. init (self, parent) self.pack() widget Button(self, text 'Quit' widget.pack(side LEFT) def quit(self) ans askokcancel('Verify exit', if ans Frame.quit(self) if name ' main ' Quitter().mainloop() This module is mostly meant to be used elsewhere, but puts up the button it implements when run standalone. Figure 7-10 shows the Quit button...

Example PPEGui Tourscrolledcanvaspy

Def init (self, parent None, color 'brown') Frame. init (self, parent) self.pack(expand YES, fill BOTH) expandable canv Canvas(self, bg color, relief SUNKEN) canv.config(width 300, height 200) area size canv.config(scrollregion (0,0,300, 1000)) canv.config(highlightthickness 0) to border sbar Scrollbar(self) sbar.config(command canv.yview) canv.config(yscrollcommand sbar.set) moves other sbar.pack(side RIGHT, fill Y) first clip last canv.pack(side LEFT, expand YES, fill BOTH) clipped first...

Example PPEGui Toursimpleeditpy

add common edit tools to scrolled text by inheritance composition (embedding) would work just as well here this is not robust see PyEdit for a feature superset from tkSimpleDialog import askstring from tkFileDialog import asksaveasfilename from scrolledtext import ScrolledText class SimpleEditor(ScrolledText) for more def init (self, parent None, file None) frm Frame(parent) frm.pack(fill X) Button(frm, text 'Save', command self.onSave).pack(side LEFT) Button(frm, text 'Cut', command...

Example PPEGui Tourtoplevelpy

From Tkinter import Toplevel, Button, Label winl Toplevel() two independent windows win2 Toplevel() but part of same process Button(win1, text 'Spam', command sys.exit).pack() Button(win2, text 'SPAM', command sys.exit).pack() Label(text 'Popups').pack() on default Tk() root window The toplevelo script gets a root window by default (that's what the Label is attached to, since it doesn't specify a real parent), but also creates two standalone Toplevel windows that appear and function...

Example PPEIntegrate EmbedBasicsmakefilebasics

build all 5 basic embedding examples with external module libs linked in source setup-pp-embed.csh if needed -lgdbm -ltk8.0 -ltcl8.0 -lX11 -lm -ldl BASICS embed-simple embed-string embed-object embed-dict embed-bytecode gcc embed *.o (PYLIB) (LIBS) -g -export-dynamic -o embed * This version links in Tkinter libraries because the Python library file it uses was built with Tkinter enabled. You may have to link in arbitrarily many more externals for your Python library, and frankly, chasing down...

Example PPEIntegrate EmbedHigh LevelApippembedh

* AN ENHANCED PYTHON EMBEDDED-CALL INTERFACE * Wraps Python's run-time embedding API functions for easy use. * Most utilities assume the call is qualified by an enclosing module * (namespace). The module can be a file-name reference or a dummy module * created to provide a namespace for file-less strings. These routines * automate debugging, module (re)loading, input output * Python is automatically initialized when the first API call occurs. * Input output conversions use the standard Python...

Example PPEIntegrate EmbedInventoryvalidatepy

embedded validation code, run from C input vars PRODUCT, QUANTITY, BUYER output vars ERRORS, WARNINGS import string all python tools are available import inventory plus C extensions, Python msgs, errs , warning, error message lists if PRODUCT not in inventory.skus( ) this errs.append('bad-product') from a user- elif QUANTITY > inventory.stock(PRODUCT) inventory.reduce(PRODUCT, QUANTITY) if inventory.stock(PRODUCT) QUANTITY < 2 msgs.append('reorder-soon ' + 'PRODUCT') first, last BUYER 0 ,...

Example PPEIntegrate ExtendStacksexttimepy

time the C stack module and type extensions versus the object chapter's Python stack implementations from PP2E.Dstruct.Basic.timer import test from PP2E.Dstruct.Basic import stackl from PP2E.Dstruct.Basic import stack2 + slice from PP2E.Dstruct.Basic import stack3 tuples from PP2E.Dstruct.Basic import stack4 append pop rept, pushes, pops, items 200, 200, 200, 200 default 200 * (600 rept, pushes, pops, items map(int, argv 1 ) except pass print 'reps d * push d+pop d+fetch d ' (rept, pushes,...

Example PPEIntegrate ExtendSwigmakefilehellolibswig

Use SWIG to integrate hellolib.c for use in Python programs. unless you've run make install SWIG . myswig hellowrap.so hellolib wrap.o (LIB) hellolib.o ld -shared hellolib wrap.o (LIB) hellolib.o -o hellowrap.so generated wrapper module code hellolib wrap.o hellolib wrap.c (LIB) hellolib.h gcc hellolib_wrap.c -c -g -I (LIB) -I (PY) Include -I (PY) (SWIG) -python -I (LIB) hellolib.i C library code (in another directory) (LIB) hellolib.o (LIB) hellolib.c (LIB) hellolib.h gcc (LIB) hellolib.c -c...

Example PPEIntegrate ExtendSwig Shadowmainsubclasspy

From number import Number sublass C++ class in Python (shadow print 'in Python add ' Number.add(self, other) def mul(self, other) print 'in Python mul ' self.data self.data * other num MyNumber(l) num.add(4) num.display() num.sub(2) num.display( ) using Python subclass of shadow class add( ) is specialized in Python num.data 99 print num.data num.display( ) Now we get extra messages out of add calls, and mul changes the C++ class's data member automatically when it assigns self.data mark toy...

Example PPEInternet CgiWeb Basicsgetfilecgi

usr bin python Display any cgi (or other) server-side file without running it. The filename can be passed in a URL param or form field e.g., Users can cut-and-paste or View source to save file locally. On IE, running the text plain version (formatted 0) sometimes pops up Notepad, but end-of-lines are not always in DOS format Netscape shows the text correctly in the browser page instead. Sending the file in text html mode works on both browsers--text is displayed in the browser response page...