Macintosh Library Modules

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Macintosh Library Modules

Release 2.3.4

Guido van Rossum


Fred L. Drake, Jr., editor

May 20, 2004

PythonLabs
Email: [email protected]
Copyright
c 2001, 2002, 2003 Python Software Foundation. All rights reserved.
Copyright
c 2000 BeOpen.com. All rights reserved.
Copyright
c 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright
c 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See the end of this document for complete license and permissions information.
Abstract

This library reference manual documents Python’s extensions for the Macintosh. It should be used in conjunction
with the Python Library Reference, which documents the standard library and built-in types.
This manual assumes basic knowledge about the Python language. For an informal introduction to Python, see the
Python Tutorial; the Python Reference Manual remains the highest authority on syntactic and semantic questions.
Finally, the manual entitled Extending and Embedding the Python Interpreter describes how to add new extensions
to Python and how to embed it in other applications.
CONTENTS

1 Using Python on a Mac OS 9 Macintosh 1


1.1 Getting and Installing MacPython-OSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Getting and Installing MacPython-OS9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 The IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 MacPython Modules 7
2.1 mac — Implementations for the os module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 macpath — MacOS path manipulation functions . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 macfs — Various file system services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 ic — Access to Internet Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.5 MacOS — Access to Mac OS interpreter features . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.6 macostools — Convenience routines for file manipulation . . . . . . . . . . . . . . . . . . . 13
2.7 findertools — The finder’s Apple Events interface . . . . . . . . . . . . . . . . . . . . . . 13
2.8 EasyDialogs — Basic Macintosh dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.9 FrameWork — Interactive application framework . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.10 autoGIL — Global Interpreter Lock handling in event loops . . . . . . . . . . . . . . . . . . . 19

3 MacPython OSA Modules 21


3.1 gensuitemodule — Generate OSA stub packages . . . . . . . . . . . . . . . . . . . . . . . 22
3.2 aetools — OSA client support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3 aepack — Conversion between Python variables and AppleEvent data containers . . . . . . . . 23
3.4 aetypes — AppleEvent objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.5 MiniAEFrame — Open Scripting Architecture server support . . . . . . . . . . . . . . . . . . 26

4 MacOS Toolbox Modules 27


4.1 Carbon.AE — Apple Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.2 Carbon.AH — Apple Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3 Carbon.App — Appearance Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.4 Carbon.CF — Core Foundation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.5 Carbon.CG — Core Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.6 Carbon.CarbonEvt — Carbon Event Manager . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.7 Carbon.Cm — Component Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.8 Carbon.Ctl — Control Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.9 Carbon.Dlg — Dialog Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.10 Carbon.Evt — Event Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.11 Carbon.Fm — Font Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.12 Carbon.Folder — Folder Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.13 Carbon.Help — Help Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.14 Carbon.List — List Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.15 Carbon.Menu — Menu Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.16 Carbon.Mlte — MultiLingual Text Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.17 Carbon.Qd — QuickDraw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.18 Carbon.Qdoffs — QuickDraw Offscreen . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

i
4.19 Carbon.Qt — QuickTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.20 Carbon.Res — Resource Manager and Handles . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.21 Carbon.Scrap — Scrap Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.22 Carbon.Snd — Sound Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.23 Carbon.TE — TextEdit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.24 Carbon.Win — Window Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.25 ColorPicker — Color selection dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

5 Undocumented Modules 31
5.1 applesingle — AppleSingle decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.2 buildtools — Helper module for BuildApplet and Friends . . . . . . . . . . . . . . . . . . . 31
5.3 py resource — Resources from Python code . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.4 cfmfile — Code Fragment Resource module . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.5 icopen — Internet Config replacement for open() . . . . . . . . . . . . . . . . . . . . . . . 31
5.6 macerrors — Mac OS Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.7 macresource — Locate script resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.8 Nav — NavServices calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.9 mkcwproject — Create CodeWarrior projects . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.10 nsremote — Wrapper around Netscape OSA modules . . . . . . . . . . . . . . . . . . . . . . 32
5.11 PixMapWrapper — Wrapper for PixMap objects . . . . . . . . . . . . . . . . . . . . . . . . 32
5.12 preferences — Application preferences manager . . . . . . . . . . . . . . . . . . . . . . . . 32
5.13 pythonprefs — Preferences manager for Python . . . . . . . . . . . . . . . . . . . . . . . . 32
5.14 quietconsole — Non-visible standard output . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.15 videoreader — Read QuickTime movies . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.16 W — Widgets built on FrameWork . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.17 waste — non-Apple TextEdit replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

A History and License 35


A.1 History of the software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
A.2 Terms and conditions for accessing or otherwise using Python . . . . . . . . . . . . . . . . . . . 36

Module Index 39

Index 41

ii
CHAPTER

ONE

Using Python on a Mac OS 9 Macintosh

Using Python on a Macintosh, especially on Mac OS 9 (MacPython-OSX includes a complete U NIX Python) can
seem like something completely different than using it on a U NIX-like or Windows system. Most of the Python
documentation, both the “official” documentation and published books, describe only how Python is used on these
systems, causing confusion for the new user of MacPython-OS9. This chapter gives a brief introduction to the
specifics of using Python on a Macintosh.
The section on the IDE (see Section 1.3) is relevant to MacPython-OSX too.

1.1 Getting and Installing MacPython-OSX


As of Python 2.3a2 the only sure way of getting MacPython-OSX on your machine is getting a source distribution
and building what is called a ”framework Python”. The details are in the file ‘Mac/OSX/README’.
As binary installers become available the details will be posted to http://www.cwi.nl/˜jack/macpython.html.
What you get after installing is a number of things:

• A ‘MacPython-2.3’ folder in your ‘Applications’ folder. In here you find the PythonIDE Integrated Devel-
opment Environment; PythonLauncher, which handles double-clicking Python scripts from the Finder; and
the Package Manager.
• A fairly standard U NIX commandline Python interpreter in ‘/usr/local/bin/python’, but without the usual
‘/usr/local/lib/python’.
• A framework ‘/Library/Frameworks/Python.framework’, where all the action really is, but which you usually
do not have to be aware of.

To uninstall MacPython you can simply remove these three things.


PythonIDE contains an Apple Help Viewer book called ”MacPython Help” which you can access through its help
menu. If you are completely new to Python you should start reading the IDE introduction in that document.
If you are familiar with Python on other U NIX platforms you should read the section on running Python scripts
from the U NIX shell.

1.1.1 How to run a Python script

Your best way to get started with Python on Mac OS X is through the PythonIDE integrated development envi-
ronment, see section 1.3 and use the Help menu when the IDE is running.
If you want to run Python scripts from the Terminal window command line or from the Finder you first need
an editor to create your script. Mac OS X comes with a number of standard U NIX command line editors, vi and
emacs among them. If you want a more Mac-like editor BBEdit or TextWrangler from Bare Bones Software (see
http://www.barebones.com/products/bbedit/index.shtml) are good choices. Their freeware BBEdit Lite is officially
discontinued but still available. AppleWorks or any other word processor that can save files in ASCII is also a
possibility, but TextEdit is not: it saves in ‘.rtf’ format only.

1
To run your script from the Terminal window you must make sure that ‘/usr/local/bin’ is in your shell search path
before ‘/usr/bin’, where the Apple-supplied Python lives (which is version 2.2, as of Mac OS X 10.2.4).
To run your script from the Finder you have two options:

• Drag it to PythonLauncher
• Select PythonLauncher as the default application to open your script (or any .py script) through the finder
Info window and double-click it.

PythonLauncher has various preferences to control how your script is launched. Option-dragging allows you to
change these for one invocation, or use its Preferences menu to change things globally.

1.1.2 Running scripts with a GUI

There is one Mac OS X quirk that you need to be aware of: programs that talk to the Aqua window manager (in
other words, anything that has a GUI) need to be run in a special way. Use pythonw instead of python to start
such scripts.

1.1.3 configuration

MacPython honours all standard U NIX environment variables such as PYTHONPATH, but setting these variables
for programs started from the Finder is non-standard as the Finder does not read your ‘.profile’ or ‘.cshrc’ at
startup. You need to create a file ‘˜/.MacOSX/environment.plist’. See Apple’s Technical Document QA1067 for
details.
Installing additional Python packages is most easily done through the Package Manager, see the MacPython Help
Book for details.

1.2 Getting and Installing MacPython-OS9


The most recent release version as well as possible newer experimental versions are best found at the MacPython
page maintained by Jack Jansen: http://homepages.cwi.nl/˜jack/macpython.html.
Please refer to the ‘README’ included with your distribution for the most up-to-date instructions.
Note that MacPython-OS9 runs fine on Mac OS X, and it runs in native mode, not in the Classic environment.
Unless you have specific requirements for a CFM-based Python there is no reason not to use MacPython-OSX,
though.

1.2.1 Entering the interactive Interpreter

The interactive interpreter that you will see used in Python documentation is started by double-clicking the
PythonInterpreter icon, which looks like a 16-ton weight falling. You should see the version information and
the ‘>>> ’ prompt. Use it exactly as described in the standard documentation.

1.2.2 How to run a Python script

There are several ways to run an existing Python script; two common ways to run a Python script are “drag and
drop” and “double clicking”. Other ways include running it from within the IDE (see Section 1.3), or launching
via AppleScript.

2 Chapter 1. Using Python on a Mac OS 9 Macintosh


Drag and drop

One of the easiest ways to launch a Python script is via “Drag and Drop”. This is just like launching a text file
in the Finder by “dragging” it over your word processor’s icon and “dropping” it there. Make sure that you use
an icon referring to the PythonInterpreter, not the IDE or Idle icons which have different behaviour which is
described below.
Some things that might have gone wrong:

• A window flashes after dropping the script onto the PythonInterpreter, but then disappears. Most likely
this is a configuration issue; your PythonInterpreter is setup to exit immediately upon completion, but
your script assumes that if it prints something that text will stick around for a while. To fix this, see section
1.2.5.
• When you waved the script icon over the PythonInterpreter, the PythonInterpreter icon did not hilight.
Most likely the Creator code and document type is unset (or set incorrectly) – this often happens when a file
originates on a non-Mac computer. See section 1.2.2 for more details.

Set Creator and Double Click

If the script that you want to launch has the appropriate Creator Code and File Type you can simply double-click
on the script to launch it. To be “double-clickable” a file needs to be of type ‘TEXT’, with a creator code of
‘Pyth’.
Setting the creator code and filetype can be done with the IDE (see sections 1.3.2 and 1.3.4), with an editor with a
Python mode (BBEdit) – see section 1.2.4, or with assorted other Mac utilities, but a script (‘fixfiletypes.py’) has
been included in the MacPython distribution, making it possible to set the proper Type and Creator Codes with
Python.
The ‘fixfiletypes.py’ script will change the file type and creator codes for the indicated directory. To use
‘fixfiletypes.py’:

1. Locate it in the ‘scripts’ folder of the ‘Mac’ folder of the MacPython distribution.
2. Put all of the scripts that you want to fix in a folder with nothing else in it.
3. Double-click on the ‘fixfiletypes.py’ icon.
4. Navigate into the folder of files you want to fix, and press the “Select current folder” button.

1.2.3 Simulating command line arguments

There are two ways to simulate command-line arguments with MacPython-OS9.

1. via Interpreter options


• Hold the option-key down when launching your script. This will bring up a dialog box of Python
Interpreter options.
• Click “Set U NIX-style command line..” button.
• Type the arguments into the “Argument” field.
• Click “OK”
• Click “Run”.
2. via drag and drop If you save the script as an applet (see Section 1.3.4), you can also simulate some
command-line arguments via “Drag-and-Drop”. In this case, the names of the files that were dropped
onto the applet will be appended to sys.argv, so that it will appear to the script as though they had been
typed on a command line. As on U NIX systems, the first item in sys.srgv is the path to the applet, and
the rest are the files dropped on the applet.

1.2. Getting and Installing MacPython-OS9 3


1.2.4 Creating a Python script

Since Python scripts are simply text files, they can be created in any way that text files can be created, but some
special tools also exist with extra features.

In an editor

You can create a text file with any word processing program such as MSWord or AppleWorks but you need to
make sure that the file is saved as “ASCII” or “plain text”.

Editors with Python modes

Several text editors have additional features that add functionality when you are creating a Python script. These
can include coloring Python keywords to make your code easier to read, module browsing, or a built-in debugger.
These include Alpha, Pepper, and BBedit, and the MacPython IDE (Section 1.3).

BBedit

If you use BBEdit to create your scripts you will want to tell it about the Python creator code so that you can
simply double click on the saved file to launch it.

• Launch BBEdit.
• Select “Preferences” from the “Edit” menu.
• Select “File Types” from the scrolling list.
• click on the “Add...” button and navigate to PythonInterpreter in the main directory of the MacPython
distribution; click “open”.
• Click on the “Save” button in the Preferences panel.

1.2.5 Configuration

The MacPython distribution comes with EditPythonPrefs, an applet which will help you to customize the
MacPython environment for your working habits.

EditPythonPrefs

EditPythonPrefs gives you the capability to configure Python to behave the way you want it to. There are two
ways to use EditPythonPrefs, you can use it to set the preferences in general, or you can drop a particular Python
engine onto it to customize only that version. The latter can be handy if, for example, you want to have a second
copy of the PythonInterpreter that keeps the output window open on a normal exit even though you prefer to
normally not work that way.
To change the default preferences, simply double-click on EditPythonPrefs. To change the preferences only for
one copy of the Interpreter, drop the icon for that copy onto EditPythonPrefs. You can also use EditPythonPrefs
in this fashion to set the preferences of the Python IDE and any applets you create – see section 1.3.4.

Adding modules to the Module Search Path

When executing an import statement, Python looks for modules in places defined by the sys.path To edit the
sys.path on a Mac, launch EditPythonPrefs, and enter them into the largish field at the top (one per line).
Since MacPython defines a main Python directory, the easiest thing is to add folders to search within the main
Python directory. To add a folder of scripts that you created called “My Folder” located in the main Python Folder,
enter ‘$(PYTHON):My Folder’ onto a new line.

4 Chapter 1. Using Python on a Mac OS 9 Macintosh


To add the Desktop under OS 9 or below, add ‘StartupDriveName:Desktop Folder’ on a new line.

Default startup options

The “Default startup options...” button in the EditPythonPrefs dialog box gives you many options including the
ability to keep the “Output” window open after the script terminates, and the ability to enter interactive mode
after the termination of the run script. The latter can be very helpful if you want to examine the objects that were
created during your script.

1.3 The IDE


The Python IDE (Integrated Development Environment) is a separate application that acts as a text editor for your
Python code, a class browser, a graphical debugger, and more.

1.3.1 Using the “Python Interactive” window

Use this window like you would the PythonInterpreter, except that you cannot use the “Drag and drop” method
above. Instead, dropping a script onto the Python IDE icon will open the file in a separate script window (which
you can then execute manually – see section 1.3.3).

1.3.2 Writing a Python Script

In addition to using the Python IDE interactively, you can also type out a complete Python program, saving it
incrementally, and execute it or smaller selections of it.
You can create a new script, open a previously saved script, and save your currently open script by selecting the
appropriate item in the “File” menu. Dropping a Python script onto the Python IDE will open it for editting.
If you try to open a script with the Python IDE but either can’t locate it from the “Open” dialog box, or you get
an error message like “Can’t open file of type ...” see section 1.2.2.
When the Python IDE saves a script, it uses the creator code settings which are available by clicking on the small
black triangle on the top right of the document window, and selecting “save options”. The default is to save the file
with the Python IDE as the creator, this means that you can open the file for editing by simply double-clicking on
its icon. You might want to change this behaviour so that it will be opened by the PythonInterpreter, and run. To
do this simply choose “Python Interpreter” from the “save options”. Note that these options are associated with
the file not the application.

1.3.3 Executing a script from within the IDE

You can run the script in the frontmost window of the Python IDE by hitting the run all button. You should be
aware, however that if you use the Python convention ‘if name == " main ":’ the script will not
be “ main ” by default. To get that behaviour you must select the “Run as main ” option from the small
black triangle on the top right of the document window. Note that this option is associated with the file not the
application. It will stay active after a save, however; to shut this feature off simply select it again.

1.3.4 “Save as” versus “Save as Applet”

When you are done writing your Python script you have the option of saving it as an “applet” (by selecting “Save
as applet” from the “File” menu). This has a significant advantage in that you can drop files or folders onto it,
to pass them to the applet the way command-line users would type them onto the command-line to pass them as
arguments to the script. However, you should make sure to save the applet as a separate file, do not overwrite the
script you are writing, because you will not be able to edit it again.

1.3. The IDE 5


Accessing the items passed to the applet via “drag-and-drop” is done using the standard sys.argv mechanism.
See the general documentation for more
Note that saving a script as an applet will not make it runnable on a system without a Python installation.

6 Chapter 1. Using Python on a Mac OS 9 Macintosh


CHAPTER

TWO

MacPython Modules

The following modules are only available on the Macintosh, and are documented here:
mac Implementations for the os module.
macpath MacOS path manipulation functions.
macfs Support for FSSpec, the Alias Manager, finder aliases, and the Standard File package.
ic Access to Internet Config.
MacOS Access to Mac OS-specific interpreter features.
macostools Convenience routines for file manipulation.
findertools Wrappers around the finder’s Apple Events interface.
EasyDialogs Basic Macintosh dialogs.
FrameWork Interactive application framework.
autoGIL Global Interpreter Lock handling in event loops.

2.1 mac — Implementations for the os module


This module implements the Mac OS 9 operating system dependent functionality provided by the standard module
os. It is best accessed through the os module. This module is only available in MacPython-OS9, on MacPython-
OSX posix is used.
The following functions are available in this module: chdir(), close(), dup(), fdopen(), getcwd(),
lseek(), listdir(), mkdir(), open(), read(), rename(), rmdir(), stat(), sync(),
unlink(), write(), as well as the exception error. Note that the times returned by stat() are floating-
point values, like all time values in MacPython-OS9.

2.2 macpath — MacOS path manipulation functions


This module is the Macintosh implementation of the os.path module. It is most portably accessed as os.path.
Refer to the Python Library Reference for documentation of os.path.
The following functions are available in this module: normcase(), normpath(), isabs(), join(),
split(), isdir(), isfile(), walk(), exists(). For other functions available in os.path dummy
counterparts are available.

2.3 macfs — Various file system services


Deprecated since release 2.3. The macfs module should be considered obsolete. For FSSpec, FSRef and
Alias handling use the Carbon.File or Carbon.Folder module. For file dialogs use the EasyDialogs module.
This module provides access to Macintosh FSSpec handling, the Alias Manager, finder aliases and the Standard
File package.
Whenever a function or method expects a file argument, this argument can be one of three things: (1) a full or

7
partial Macintosh pathname, (2) an FSSpec object or (3) a 3-tuple (wdRefNum, parID, name) as described
in Inside Macintosh: Files. An FSSpec can point to a non-existing file, as long as the folder containing the file
exists. Under MacPython the same is true for a pathname, but not under unix-Pyton because of the way pathnames
and FSRefs works. See Apple’s documentation for details.
A description of aliases and the Standard File package can also be found there.
FSSpec(file)
Create an FSSpec object for the specified file.
RawFSSpec(data)
Create an FSSpec object given the raw data for the C structure for the FSSpec as a string. This is mainly
useful if you have obtained an FSSpec structure over a network.
RawAlias(data)
Create an Alias object given the raw data for the C structure for the alias as a string. This is mainly useful
if you have obtained an FSSpec structure over a network.
FInfo()
Create a zero-filled FInfo object.
ResolveAliasFile(file)
Resolve an alias file. Returns a 3-tuple (fsspec, isfolder, aliased) where fsspec is the resulting FSSpec
object, isfolder is true if fsspec points to a folder and aliased is true if the file was an alias in the first place
(otherwise the FSSpec object for the file itself is returned).
StandardGetFile([type, ... ])
Present the user with a standard “open input file” dialog. Optionally, you can pass up to four 4-character
file types to limit the files the user can choose from. The function returns an FSSpec object and a flag
indicating that the user completed the dialog without cancelling.
PromptGetFile(prompt[, type, ... ])
Similar to StandardGetFile() but allows you to specify a prompt which will be displayed at the top
of the dialog.
StandardPutFile(prompt[, default ])
Present the user with a standard “open output file” dialog. prompt is the prompt string, and the optional de-
fault argument initializes the output file name. The function returns an FSSpec object and a flag indicating
that the user completed the dialog without cancelling.
GetDirectory([prompt ])
Present the user with a non-standard “select a directory” dialog. You have to first open the directory before
clicking on the “select current directory” button. prompt is the prompt string which will be displayed at the
top of the dialog. Return an FSSpec object and a success-indicator.
SetFolder([fsspec ])
Set the folder that is initially presented to the user when one of the file selection dialogs is presented. fsspec
should point to a file in the folder, not the folder itself (the file need not exist, though). If no argument is
passed the folder will be set to the current directory, i.e. what os.getcwd() returns.
Note that starting with system 7.5 the user can change Standard File behaviour with the “general controls”
control panel, thereby making this call inoperative.
FindFolder(where, which, create)
Locates one of the “special” folders that MacOS knows about, such as the trash or the Preferences folder.
where is the disk to search, which is the 4-character string specifying which folder to locate. Setting create
causes the folder to be created if it does not exist. Returns a (vrefnum, dirid) tuple.
The constants for where and which can be obtained from the standard module Carbon.Folders.
NewAliasMinimalFromFullPath(pathname)
Return a minimal alias object that points to the given file, which must be specified as a full pathname.
This is the only way to create an Alias pointing to a non-existing file.
FindApplication(creator)
Locate the application with 4-character creator code creator. The function returns an FSSpec object point-
ing to the application.

8 Chapter 2. MacPython Modules


2.3.1 FSSpec Objects
data
The raw data from the FSSpec object, suitable for passing to other applications, for instance.
as pathname()
Return the full pathname of the file described by the FSSpec object.
as tuple()
Return the (wdRefNum, parID, name) tuple of the file described by the FSSpec object.
NewAlias([file ])
Create an Alias object pointing to the file described by this FSSpec. If the optional file parameter is present
the alias will be relative to that file, otherwise it will be absolute.
NewAliasMinimal()
Create a minimal alias pointing to this file.
GetCreatorType()
Return the 4-character creator and type of the file.
SetCreatorType(creator, type)
Set the 4-character creator and type of the file.
GetFInfo()
Return a FInfo object describing the finder info for the file.
SetFInfo(finfo)
Set the finder info for the file to the values given as finfo (an FInfo object).
GetDates()
Return a tuple with three floating point values representing the creation date, modification date and backup
date of the file.
SetDates(crdate, moddate, backupdate)
Set the creation, modification and backup date of the file. The values are in the standard floating point
format used for times throughout Python.

2.3.2 Alias Objects


data
The raw data for the Alias record, suitable for storing in a resource or transmitting to other programs.
Resolve([file ])
Resolve the alias. If the alias was created as a relative alias you should pass the file relative to which it is.
Return the FSSpec for the file pointed to and a flag indicating whether the Alias object itself was modified
during the search process. If the file does not exist but the path leading up to it does exist a valid fsspec is
returned.
GetInfo(num)
An interface to the C routine GetAliasInfo().
Update(file[, file2 ])
Update the alias to point to the file given. If file2 is present a relative alias will be created.
Note that it is currently not possible to directly manipulate a resource as an Alias object. Hence, after calling
Update() or after Resolve() indicates that the alias has changed the Python program is responsible for
getting the data value from the Alias object and modifying the resource.

2.3.3 FInfo Objects

See Inside Macintosh: Files for a complete description of what the various fields mean.
Creator
The 4-character creator code of the file.

2.3. macfs — Various file system services 9


Type
The 4-character type code of the file.
Flags
The finder flags for the file as 16-bit integer. The bit values in Flags are defined in standard module MACFS.
Location
A Point giving the position of the file’s icon in its folder.
Fldr
The folder the file is in (as an integer).

2.4 ic — Access to Internet Config


This module provides access to Macintosh Internet Config package, which stores preferences for Internet programs
such as mail address, default homepage, etc. Also, Internet Config contains an elaborate set of mappings from
Macintosh creator/type codes to foreign filename extensions plus information on how to transfer files (binary,
ascii, etc.). Since MacOS 9, this module is a control panel named Internet.
There is a low-level companion module icglue which provides the basic Internet Config access functionality.
This low-level module is not documented, but the docstrings of the routines document the parameters and the
routine names are the same as for the Pascal or C API to Internet Config, so the standard IC programmers’
documentation can be used if this module is needed.
The ic module defines the error exception and symbolic names for all error codes Internet Config can produce;
see the source for details.
exception error
Exception raised on errors in the ic module.
The ic module defines the following class and function:
class IC([signature[, ic ]])
Create an Internet Config object. The signature is a 4-character creator code of the current application
(default ’Pyth’) which may influence some of ICs settings. The optional ic argument is a low-level
icglue.icinstance created beforehand, this may be useful if you want to get preferences from a
different config file, etc.
launchurl(url[, hint ])
parseurl(data[, start[, end[, hint ]]])
mapfile(file)
maptypecreator(type, creator[, filename ])
settypecreator(file)
These functions are “shortcuts” to the methods of the same name, described below.

2.4.1 IC Objects

IC objects have a mapping interface, hence to obtain the mail address you simply get ic[’MailAddress’].
Assignment also works, and changes the option in the configuration file.
The module knows about various datatypes, and converts the internal IC representation to a “logical” Python data
structure. Running the ic module standalone will run a test program that lists all keys and values in your IC
database, this will have to serve as documentation.
If the module does not know how to represent the data it returns an instance of the ICOpaqueData type, with
the raw data in its data attribute. Objects of this type are also acceptable values for assignment.
Besides the dictionary interface, IC objects have the following methods:
launchurl(url[, hint ])
Parse the given URL, lauch the correct application and pass it the URL. The optional hint can be a scheme
name such as ’mailto:’, in which case incomplete URLs are completed with this scheme. If hint is not
provided, incomplete URLs are invalid.

10 Chapter 2. MacPython Modules


parseurl(data[, start[, end[, hint ]]])
Find an URL somewhere in data and return start position, end position and the URL. The optional start and
end can be used to limit the search, so for instance if a user clicks in a long text field you can pass the whole
text field and the click-position in start and this routine will return the whole URL in which the user clicked.
As above, hint is an optional scheme used to complete incomplete URLs.
mapfile(file)
Return the mapping entry for the given file, which can be passed as either a filename or an
macfs.FSSpec() result, and which need not exist.
The mapping entry is returned as a tuple (version, type, creator, postcreator, flags, extension,
appname, postappname, mimetype, entryname), where version is the entry version number, type is the
4-character filetype, creator is the 4-character creator type, postcreator is the 4-character creator code of
an optional application to post-process the file after downloading, flags are various bits specifying whether
to transfer in binary or ascii and such, extension is the filename extension for this file type, appname is the
printable name of the application to which this file belongs, postappname is the name of the postprocessing
application, mimetype is the MIME type of this file and entryname is the name of this entry.
maptypecreator(type, creator[, filename ])
Return the mapping entry for files with given 4-character type and creator codes. The optional filename
may be specified to further help finding the correct entry (if the creator code is ’????’, for instance).
The mapping entry is returned in the same format as for mapfile.
settypecreator(file)
Given an existing file, specified either as a filename or as an macfs.FSSpec() result, set its creator and
type correctly based on its extension. The finder is told about the change, so the finder icon will be updated
quickly.

2.5 MacOS — Access to Mac OS interpreter features


This module provides access to MacOS specific functionality in the Python interpreter, such as how the interpreter
eventloop functions and the like. Use with care.
Note the capitalization of the module name; this is a historical artifact.
runtimemodel
Either’carbon’ or ’macho’. This signifies whether this Python uses the Mac OS X and Mac OS 9
compatible CarbonLib style or the Mac OS X-only Mach-O style. In earlier versions of Python the value
could also be ’ppc’ for the classic Mac OS 8 runtime model.
linkmodel
The way the interpreter has been linked. As extension modules may be incompatible between linking mod-
els, packages could use this information to give more decent error messages. The value is one of ’static’
for a statically linked Python, ’framework’ for Python in a Mac OS X framework, ’shared’ for
Python in a standard unix shared library and ’cfm’ for the Mac OS 9-compatible Python.
exception Error
This exception is raised on MacOS generated errors, either from functions in this module or from other
mac-specific modules like the toolbox interfaces. The arguments are the integer error code (the OSErr
value) and a textual description of the error code. Symbolic names for all known error codes are defined in
the standard module macerrors.
SetEventHandler(handler)
In the inner interpreter loop Python will occasionally check for events, unless disabled with
ScheduleParams(). With this function you can pass a Python event-handler function that will be called
if an event is available. The event is passed as parameter and the function should return non-zero if the event
has been fully processed, otherwise event processing continues (by passing the event to the console window
package, for instance).
Call SetEventHandler() without a parameter to clear the event handler. Setting an event handler while
one is already set is an error.
Availability: MacPython-OS9.

2.5. MacOS — Access to Mac OS interpreter features 11


SchedParams([doint[, evtmask[, besocial[, interval[, bgyield ]]]]])
Influence the interpreter inner loop event handling. Interval specifies how often (in seconds, floating point)
the interpreter should enter the event processing code. When true, doint causes interrupt (command-dot)
checking to be done. evtmask tells the interpreter to do event processing for events in the mask (redraws,
mouseclicks to switch to other applications, etc). The besocial flag gives other processes a chance to run.
They are granted minimal runtime when Python is in the foreground and bgyield seconds per interval when
Python runs in the background.
All parameters are optional, and default to the current value. The return value of this function is a tuple with
the old values of these options. Initial defaults are that all processing is enabled, checking is done every
quarter second and the processor is given up for a quarter second when in the background.
The most common use case is to call SchedParams(0, 0) to completely disable event handling in the
interpreter mainloop.
Availability: MacPython-OS9.
HandleEvent(ev)
Pass the event record ev back to the Python event loop, or possibly to the handler for the sys.stdout
window (based on the compiler used to build Python). This allows Python programs that do their own event
handling to still have some command-period and window-switching capability.
If you attempt to call this function from an event handler set through SetEventHandler() you will get
an exception.
Availability: MacPython-OS9.
GetErrorString(errno)
Return the textual description of MacOS error code errno.
splash(resid)
This function will put a splash window on-screen, with the contents of the DLOG resource specified by
resid. Calling with a zero argument will remove the splash screen. This function is useful if you want an
applet to post a splash screen early in initialization without first having to load numerous extension modules.
Availability: MacPython-OS9.
DebugStr(message [, object ])
On Mac OS 9, drop to the low-level debugger with message message. The optional object argument is not
used, but can easily be inspected from the debugger. On Mac OS X the string is simply printed to stderr.
Note that you should use this function with extreme care: if no low-level debugger like MacsBug is installed
this call will crash your system. It is intended mainly for developers of Python extension modules.
SysBeep()
Ring the bell.
GetTicks()
Get the number of clock ticks (1/60th of a second) since system boot.
GetCreatorAndType(file)
Return the file creator and file type as two four-character strings. The file parameter can be a pathname or
an FSSpec or FSRef object.
SetCreatorAndType(file, creator, type)
Set the file creator and file type. The file parameter can be a pathname or an FSSpec or FSRef object.
creator and type must be four character strings.
openrf(name [, mode ])
Open the resource fork of a file. Arguments are the same as for the built-in function open(). The object
returned has file-like semantics, but it is not a Python file object, so there may be subtle differences.
WMAvailable()
Checks whether the current process has access to the window manager. The method will return False if
the window manager is not available, for instance when running on Mac OS X Server or when logged in via
ssh, or when the current interpreter is not running from a fullblown application bundle. A script runs from
an application bundle either when it has been started with pythonw instead of python or when running as
an applet.

12 Chapter 2. MacPython Modules


On Mac OS 9 the method always returns True.

2.6 macostools — Convenience routines for file manipulation


This module contains some convenience routines for file-manipulation on the Macintosh. All file parameters can
be specified as pathnames, FSRef or FSSpec objects.
The macostools module defines the following functions:
copy(src, dst[, createpath[, copytimes ]])
Copy file src to dst. If createpath is non-zero the folders leading to dst are created if necessary. The method
copies data and resource fork and some finder information (creator, type, flags) and optionally the creation,
modification and backup times (default is to copy them). Custom icons, comments and icon position are not
copied.
copytree(src, dst)
Recursively copy a file tree from src to dst, creating folders as needed. src and dst should be specified as
pathnames.
mkalias(src, dst)
Create a finder alias dst pointing to src.
touched(dst)
Tell the finder that some bits of finder-information such as creator or type for file dst has changed. The file
can be specified by pathname or fsspec. This call should tell the finder to redraw the files icon.
BUFSIZ
The buffer size for copy, default 1 megabyte.
Note that the process of creating finder aliases is not specified in the Apple documentation. Hence, aliases created
with mkalias() could conceivably have incompatible behaviour in some cases.

2.7 findertools — The finder’s Apple Events interface


This module contains routines that give Python programs access to some functionality provided by the finder.
They are implemented as wrappers around the AppleEvent interface to the finder.
All file and folder parameters can be specified either as full pathnames, or as FSRef or FSSpec objects.
The findertools module defines the following functions:
launch(file)
Tell the finder to launch file. What launching means depends on the file: applications are started, folders are
opened and documents are opened in the correct application.
Print(file)
Tell the finder to print a file. The behaviour is identical to selecting the file and using the print command in
the finder’s file menu.
copy(file, destdir)
Tell the finder to copy a file or folder file to folder destdir. The function returns an Alias object pointing
to the new file.
move(file, destdir)
Tell the finder to move a file or folder file to folder destdir. The function returns an Alias object pointing
to the new file.
sleep()
Tell the finder to put the Macintosh to sleep, if your machine supports it.
restart()
Tell the finder to perform an orderly restart of the machine.

2.6. macostools — Convenience routines for file manipulation 13


shutdown()
Tell the finder to perform an orderly shutdown of the machine.

2.8 EasyDialogs — Basic Macintosh dialogs


The EasyDialogs module contains some simple dialogs for the Macintosh. All routines take an optional
resource ID parameter id with which one can override the DLOG resource used for the dialog, provided that the
dialog items correspond (both type and item number) to those in the default DLOG resource. See source code for
details.
The EasyDialogs module defines the following functions:
Message(str[, id[, ok=None ]])
Displays a modal dialog with the message text str, which should be at most 255 characters long. The button
text defaults to “OK”, but is set to the string argument ok if the latter is supplied. Control is returned when
the user clicks the “OK” button.
AskString(prompt[, default[, id[, ok[, cancel ]]]])
Asks the user to input a string value via a modal dialog. prompt is the prompt message, and the optional
default supplies the initial value for the string (otherwise "" is used). The text of the “OK” and “Cancel”
buttons can be changed with the ok and cancel arguments. All strings can be at most 255 bytes long.
AskString() returns the string entered or None in case the user cancelled.
AskPassword(prompt[, default[, id[, ok[, cancel ]]]])
Asks the user to input a string value via a modal dialog. Like AskString(), but with the text shown as
bullets. The arguments have the same meaning as for AskString().
AskYesNoCancel(question[, default[, yes[, no[, cancel[, id ]]]]])
Presents a dialog with prompt question and three buttons labelled “Yes”, “No”, and “Cancel”. Returns 1
for “Yes”, 0 for “No” and -1 for “Cancel”. The value of default (or 0 if default is not supplied) is returned
when the RETURN key is pressed. The text of the buttons can be changed with the yes, no, and cancel
arguments; to prevent a button from appearing, supply "" for the corresponding argument.
ProgressBar([title[, maxval[, label[, id ]]]])
Displays a modeless progress-bar dialog. This is the constructor for the ProgressBar class described
below. title is the text string displayed (default “Working...”), maxval is the value at which progress is
complete (default 0, indicating that an indeterminate amount of work remains to be done), and label is the
text that is displayed above the progress bar itself.
GetArgv([optionlist[ commandlist[, addoldfile[, addnewfile[, addfolder[, id ]]]]]])
Displays a dialog which aids the user in constructing a command-line argument list. Returns the list in
sys.argv format, suitable for passing as an argument to getopt.getopt(). addoldfile, addnewfile,
and addfolder are boolean arguments. When nonzero, they enable the user to insert into the command
line paths to an existing file, a (possibly) not-yet-existent file, and a folder, respectively. (Note: Option
arguments must appear in the command line before file and folder arguments in order to be recognized by
getopt.getopt().) Arguments containing spaces can be specified by enclosing them within single or
double quotes. A SystemExit exception is raised if the user presses the “Cancel” button.
optionlist is a list that determines a popup menu from which the allowed options are selected. Its items can
take one of two forms: optstr or (optstr, descr). When present, descr is a short descriptive string that
is displayed in the dialog while this option is selected in the popup menu. The correspondence between
optstrs and command-line arguments is:
optstr format Command-line format
x -x (short option)
x: or x= -x (short option with value)
xyz --xyz (long option)
xyz: or xyz= --xyz (long option with value)
commandlist is a list of items of the form cmdstr or (cmdstr, descr), where descr is as above. The cmdstrs
will appear in a popup menu. When chosen, the text of cmdstr will be appended to the command line as is,
except that a trailing ‘:’ or ‘=’ (if present) will be trimmed off.

14 Chapter 2. MacPython Modules


New in version 2.0.
AskFileForOpen( [message ] [, typeList ] [, defaultLocation ] [, defaultOptionFlags ] [, location ] [, client-
Name ] [, windowTitle ] [, actionButtonLabel ] [, cancelButtonLabel ] [, preferenceKey ]
[, popupExtension ] [, eventProc ] [, previewProc ] [, filterProc ] [, wanted ] )
Post a dialog asking the user for a file to open, and return the file selected or None if the user cancelled.
message is a text message to display, typeList is a list of 4-char filetypes allowable, defaultLocation is the
pathname, FSSpec or FSRef of the folder to show initially, location is the (x, y) position on the screen
where the dialog is shown, actionButtonLabel is a string to show instead of “Open” in the OK button,
cancelButtonLabel is a string to show instead of “Cancel” in the cancel button, wanted is the type of value
wanted as a return: string, unicode, FSSpec, FSRef and subtypes thereof are acceptable.
For a description of the other arguments please see the Apple Navigation Services documentation and the
EasyDialogs sourcecode.
AskFileForSave( [message ] [, savedFileName ] [, defaultLocation ] [, defaultOptionFlags ] [, location ]
[, clientName ] [, windowTitle ] [, actionButtonLabel ] [, cancelButtonLabel ] [, prefer-
enceKey ] [, popupExtension ] [, fileType ] [, fileCreator ] [, eventProc ] [, wanted ] )
Post a dialog asking the user for a file to save to, and return the file selected or None if the user cancelled.
savedFileName is the default for the file name to save to (the return value). See AskFileForOpen for a
description of the other arguments.
AskFolder( [message ] [, defaultLocation ] [, defaultOptionFlags ] [, location ] [, clientName ] [, windowTi-
tle ] [, actionButtonLabel ] [, cancelButtonLabel ] [, preferenceKey ] [, popupExtension ] [, event-
Proc ] [, filterProc ] [, wanted ] )
Post a dialog asking the user to select a folder, and return the folder selected or None if the user cancelled.
See AskFileForOpen for a description of the arguments.

2.8.1 ProgressBar Objects

ProgressBar objects provide support for modeless progress-bar dialogs. Both determinate (thermometer style)
and indeterminate (barber-pole style) progress bars are supported. The bar will be determinate if its maximum
value is greater than zero; otherwise it will be indeterminate. Changed in version 2.2: Support for indeterminate-
style progress bars was added.
The dialog is displayed immediately after creation. If the dialog’s “Cancel” button is pressed, or if Cmd-. or ESC
is typed, the dialog window is hidden and KeyboardInterrupt is raised (but note that this response does not
occur until the progress bar is next updated, typically via a call to inc() or set()). Otherwise, the bar remains
visible until the ProgressBar object is discarded.
ProgressBar objects possess the following attributes and methods:
curval
The current value (of type integer or long integer) of the progress bar. The normal access methods coerce
curval between 0 and maxval. This attribute should not be altered directly.
maxval
The maximum value (of type integer or long integer) of the progress bar; the progress bar (thermometer
style) is full when curval equals maxval. If maxval is 0, the bar will be indeterminate (barber-pole).
This attribute should not be altered directly.
title([newstr ])
Sets the text in the title bar of the progress dialog to newstr.
label([newstr ])
Sets the text in the progress box of the progress dialog to newstr.
set(value[, max ])
Sets the progress bar’s curval to value, and also maxval to max if the latter is provided. value is first
coerced between 0 and maxval. The thermometer bar is updated to reflect the changes, including a change
from indeterminate to determinate or vice versa.
inc([n ])
Increments the progress bar’s curval by n, or by 1 if n is not provided. (Note that n may be negative,

2.8. EasyDialogs — Basic Macintosh dialogs 15


in which case the effect is a decrement.) The progress bar is updated to reflect the change. If the bar is
indeterminate, this causes one “spin” of the barber pole. The resulting curval is coerced between 0 and
maxval if incrementing causes it to fall outside this range.

2.9 FrameWork — Interactive application framework


The FrameWork module contains classes that together provide a framework for an interactive Macintosh appli-
cation. The programmer builds an application by creating subclasses that override various methods of the bases
classes, thereby implementing the functionality wanted. Overriding functionality can often be done on various dif-
ferent levels, i.e. to handle clicks in a single dialog window in a non-standard way it is not necessary to override
the complete event handling.
The FrameWork is still very much work-in-progress, and the documentation describes only the most important
functionality, and not in the most logical manner at that. Examine the source or the examples for more details.
The following are some comments posted on the MacPython newsgroup about the strengths and limitations of
FrameWork:

The strong point of FrameWork is that it allows you to break into the control-flow at many
different places. W, for instance, uses a different way to enable/disable menus and that plugs right in
leaving the rest intact. The weak points of FrameWork are that it has no abstract command interface
(but that shouldn’t be difficult), that it’s dialog support is minimal and that it’s control/toolbar support
is non-existent.

The FrameWork module defines the following functions:


Application()
An object representing the complete application. See below for a description of the methods. The default
init () routine creates an empty window dictionary and a menu bar with an apple menu.
MenuBar()
An object representing the menubar. This object is usually not created by the user.
Menu(bar, title[, after ])
An object representing a menu. Upon creation you pass the MenuBar the menu appears in, the title string
and a position (1-based) after where the menu should appear (default: at the end).
MenuItem(menu, title[, shortcut, callback ])
Create a menu item object. The arguments are the menu to create, the item title string and optionally the
keyboard shortcut and a callback routine. The callback is called with the arguments menu-id, item number
within menu (1-based), current front window and the event record.
Instead of a callable object the callback can also be a string. In this case menu selection causes the lookup
of a method in the topmost window and the application. The method name is the callback string with
’domenu ’ prepended.
Calling the MenuBar fixmenudimstate() method sets the correct dimming for all menu items based
on the current front window.
Separator(menu)
Add a separator to the end of a menu.
SubMenu(menu, label)
Create a submenu named label under menu menu. The menu object is returned.
Window(parent)
Creates a (modeless) window. Parent is the application object to which the window belongs. The window
is not displayed until later.
DialogWindow(parent)
Creates a modeless dialog window.
windowbounds(width, height)
Return a (left, top, right, bottom) tuple suitable for creation of a window of given width and height.

16 Chapter 2. MacPython Modules


The window will be staggered with respect to previous windows, and an attempt is made to keep the whole
window on-screen. However, the window will however always be the exact size given, so parts may be
offscreen.
setwatchcursor()
Set the mouse cursor to a watch.
setarrowcursor()
Set the mouse cursor to an arrow.

2.9.1 Application Objects

Application objects have the following methods, among others:


makeusermenus()
Override this method if you need menus in your application. Append the menus to the attribute menubar.
getabouttext()
Override this method to return a text string describing your application. Alternatively, override the
do about() method for more elaborate “about” messages.
mainloop([mask[, wait ]])
This routine is the main event loop, call it to set your application rolling. Mask is the mask of events
you want to handle, wait is the number of ticks you want to leave to other concurrent application (default
0, which is probably not a good idea). While raising self to exit the mainloop is still supported it is not
recommended: call self. quit() instead.
The event loop is split into many small parts, each of which can be overridden. The default methods take
care of dispatching events to windows and dialogs, handling drags and resizes, Apple Events, events for
non-FrameWork windows, etc.
In general, all event handlers should return 1 if the event is fully handled and 0 otherwise (because the
front window was not a FrameWork window, for instance). This is needed so that update events and such
can be passed on to other windows like the Sioux console window. Calling MacOS.HandleEvent() is
not allowed within our dispatch or its callees, since this may result in an infinite loop if the code is called
through the Python inner-loop event handler.
asyncevents(onoff )
Call this method with a nonzero parameter to enable asynchronous event handling. This will tell the inner
interpreter loop to call the application event handler async dispatch whenever events are available. This will
cause FrameWork window updates and the user interface to remain working during long computations, but
will slow the interpreter down and may cause surprising results in non-reentrant code (such as FrameWork
itself). By default async dispatch will immedeately call our dispatch but you may override this to handle
only certain events asynchronously. Events you do not handle will be passed to Sioux and such.
The old on/off value is returned.
quit()
Terminate the running mainloop() call at the next convenient moment.
do char(c, event)
The user typed character c. The complete details of the event can be found in the event structure. This
method can also be provided in a Window object, which overrides the application-wide handler if the
window is frontmost.
do dialogevent(event)
Called early in the event loop to handle modeless dialog events. The default method simply dispatches
the event to the relevant dialog (not through the DialogWindow object involved). Override if you need
special handling of dialog events (keyboard shortcuts, etc).
idle(event)
Called by the main event loop when no events are available. The null-event is passed (so you can look at
mouse position, etc).

2.9. FrameWork — Interactive application framework 17


2.9.2 Window Objects

Window objects have the following methods, among others:


open()
Override this method to open a window. Store the MacOS window-id in self.wid and call the
do postopen() method to register the window with the parent application.
close()
Override this method to do any special processing on window close. Call the do postclose() method
to cleanup the parent state.
do postresize(width, height, macoswindowid)
Called after the window is resized. Override if more needs to be done than calling InvalRect.
do contentclick(local, modifiers, event)
The user clicked in the content part of a window. The arguments are the coordinates (window-relative), the
key modifiers and the raw event.
do update(macoswindowid, event)
An update event for the window was received. Redraw the window.
do activate(activate, event)
The window was activated (activate == 1) or deactivated (activate == 0). Handle things like focus
highlighting, etc.

2.9.3 ControlsWindow Object

ControlsWindow objects have the following methods besides those of Window objects:
do controlhit(window, control, pcode, event)
Part pcode of control control was hit by the user. Tracking and such has already been taken care of.

2.9.4 ScrolledWindow Object

ScrolledWindow objects are ControlsWindow objects with the following extra methods:
scrollbars([wantx[, wanty ]])
Create (or destroy) horizontal and vertical scrollbars. The arguments specify which you want (default:
both). The scrollbars always have minimum 0 and maximum 32767.
getscrollbarvalues()
You must supply this method. It should return a tuple (x, y) giving the current position of the scrollbars
(between 0 and 32767). You can return None for either to indicate the whole document is visible in that
direction.
updatescrollbars()
Call this method when the document has changed. It will call getscrollbarvalues() and update the
scrollbars.
scrollbar callback(which, what, value)
Supplied by you and called after user interaction. which will be ’x’ or ’y’, what will be ’-’, ’--’,
’set’, ’++’ or ’+’. For ’set’, value will contain the new scrollbar position.
scalebarvalues(absmin, absmax, curmin, curmax)
Auxiliary method to help you calculate values to return from getscrollbarvalues(). You pass docu-
ment minimum and maximum value and topmost (leftmost) and bottommost (rightmost) visible values and
it returns the correct number or None.
do activate(onoff, event)
Takes care of dimming/highlighting scrollbars when a window becomes frontmost. If you override this
method, call this one at the end of your method.

18 Chapter 2. MacPython Modules


do postresize(width, height, window)
Moves scrollbars to the correct position. Call this method initially if you override it.
do controlhit(window, control, pcode, event)
Handles scrollbar interaction. If you override it call this method first, a nonzero return value indicates the
hit was in the scrollbars and has been handled.

2.9.5 DialogWindow Objects

DialogWindow objects have the following methods besides those of Window objects:
open(resid)
Create the dialog window, from the DLOG resource with id resid. The dialog object is stored in self.wid.
do itemhit(item, event)
Item number item was hit. You are responsible for redrawing toggle buttons, etc.

2.10 autoGIL — Global Interpreter Lock handling in event loops


The autoGIL module provides a function installAutoGIL that automatically locks and unlocks Python’s
Global Interpreter Lock when running an event loop.
exception AutoGILError
Raised if the observer callback cannot be installed, for example because the current thread does not have a
run loop.
installAutoGIL()
Install an observer callback in the event loop (CFRunLoop) for the current thread, that will lock and unlock
the Global Interpreter Lock (GIL) at appropriate times, allowing other Python threads to run while the event
loop is idle.
Availability: OSX 10.1 or later.

2.10. autoGIL — Global Interpreter Lock handling in event loops 19


20
CHAPTER

THREE

MacPython OSA Modules

Python has a fairly complete implementation of the Open Scripting Architecure (OSA, also commonly referred
to as AppleScript), allowing you to control scriptable applications from your Python program, and with a fairly
pythonic interface.
For a description of the various components of AppleScript and OSA, and to get an understanding of the archi-
tecture and terminology, you should read Apple’s documentation. The ”Applescript Language Guide” explains
the conceptual model and the terminology, and documents the standard suite. The ”Open Scripting Architecture”
document explains how to use OSA from an application programmers point of view. In the Apple Help Viewer
these book sare located in the Developer Documentation, Core Technologies section.
As an example of scripting an application, the following piece of AppleScript will get the name of the frontmost
Finder window and print it:

tell application "Finder"


get name of window 1
end tell

In Python, the following code fragment will do the same:

import Finder

f = Finder.Finder()
print f.get(f.window(1).name)

As distributed the Python library includes packages that implement the standard suites, plus packages that interface
to a small number of common applications.
To send AppleEvents to an application you must first create the Python package interfacing to the terminology of
the application (what Script Editor calls the ”Dictionary”). This can be done from within the PythonIDE or by
running the ‘gensuitemodule.py’ module as a standalone program from the command line.
The generated output is a package with a number of modules, one for every suite used in the program plus an
init module to glue it all together. The Python inheritance graph follows the AppleScript inheritance
graph, so if a programs dictionary specifies that it includes support for the Standard Suite, but extends one or
two verbs with extra arguments then the output suite will contain a module Standard Suite that imports
and re-exports everything from StdSuites.Standard Suite but overrides the methods that have extra
functionality. The output of gensuitemodule is pretty readable, and contains the documentation that was in
the original AppleScript dictionary in Python docstrings, so reading it is a good source of documentation.
The output package implements a main class with the same name as the package which contains all the AppleScript
verbs as methods, with the direct object as the first argument and all optional parameters as keyword arguments.
AppleScript classes are also implemented as Python classes, as are comparisons and all the other thingies.
The main Python class implementing the verbs also allows access to the properties and elements declared
in the AppleScript class ”application”. In the current release that is as far as the object orientation goes,

21
so in the example above we need to use f.get(f.window(1).name) instead of the more Pythonic
f.window(1).name.get().
If an AppleScript identifier is not a Python identifier the name is mangled according to a small number of rules:

• spaces are replaced with underscores


• other non-alphanumeric characters are replaced with xx where xx is the hexadecimal character value
• any Python reserved word gets an underscore appended

Python also has support for creating scriptable applications in Python, but The following modules are relevant to
MacPython AppleScript support:
gensuitemodule Create a stub package from an OSA dictionary
aetools Basic support for sending Apple Events
aepack Conversion between Python variables and AppleEvent data containers.
aetypes Python representation of the Apple Event Object Model.
MiniAEFrame Support to act as an Open Scripting Architecture (OSA) server (“Apple Events”).
In addition, support modules have been pre-generated for Finder, Terminal, Explorer, Netscape,
CodeWarrior, SystemEvents and StdSuites.

3.1 gensuitemodule — Generate OSA stub packages


The gensuitemodule module creates a Python package implementing stub code for the AppleScript suites
that are implemented by a specific application, according to its AppleScript dictionary.
It is usually invoked by the user through the PythonIDE, but it can also be run as a script from the com-
mand line (pass --help for help on the options) or imported from Python code. For an example of its use see
‘Mac/scripts/genallsuites.py’ in a source distribution, which generates the stub packages that are included in the
standard library.
It defines the following public functions:
is scriptable(application)
Returns true if application, which should be passed as a pathname, appears to be scriptable. Take the
return value with a grain of salt: Internet Explorer appears not to be scriptable but definitely is.
processfile(application[, output, basepkgname, edit modnames, creatorsignature, dump, verbose ])
Create a stub package for application, which should be passed as a full pathname. For a ‘.app’ bundle
this is the pathname to the bundle, not to the executable inside the bundle; for an unbundled CFM application
you pass the filename of the application binary.
This function asks the application for its OSA terminology resources, decodes these resources and uses the
resultant data to create the Python code for the package implementing the client stubs.
output is the pathname where the resulting package is stored, if not specified a standard ”save file as”
dialog is presented to the user. basepkgname is the base package on which this package will build,
and defaults to StdSuites. Only when generating StdSuites itself do you need to specify this.
edit modnames is a dictionary that can be used to change modulenames that are too ugly after name
mangling. creator signature can be used to override the 4-char creator code, which is normally
obtained from the ‘PkgInfo’ file in the package or from the CFM file creator signature. When dump is given
it should refer to a file object, and processfile will stop after decoding the resources and dump the
Python representation of the terminology resources to this file. verbose should also be a file object, and
specifying it will cause processfile to tell you what it is doing.
processfile fromresource(application[, output, basepkgname, edit modnames, creatorsignature,
dump, verbose ])
This function does the same as processfile, except that it uses a different method to get the terminology
resources. It opens application as a resource file and reads all "aete" and "aeut" resources from
this file.

22 Chapter 3. MacPython OSA Modules


3.2 aetools — OSA client support
The aetools module contains the basic functionality on which Python AppleScript client support is built. It
also imports and re-exports the core functionality of the aetypes and aepack modules. The stub packages
generated by gensuitemodule import the relevant portions of aetools, so usually you do not need to import
it yourself. The exception to this is when you cannot use a generated suite package and need lower-level access to
scripting.
The aetools module itself uses the AppleEvent support provided by the Carbon.AE module. This has one
drawback: you need access to the window manager, see section 1.1.2 for details. This restriction may be lifted in
future releases.
The aetools module defines the following functions:
packevent(ae, parameters, attributes)
Stores parameters and attributes in a pre-created Carbon.AE.AEDesc object. parameters and
attributes are dictionaries mapping 4-character OSA parameter keys to Python objects. The objects
are packed using aepack.pack().
unpackevent(ae[, formodulename ])
Recursively unpacks a Carbon.AE.AEDesc event to Python objects. The function returns the parameter
dictionary and the attribute dictionary. The formodulename argument is used by generated stub packages
to control where AppleScript classes are looked up.
keysubst(arguments, keydict)
Converts a Python keyword argument dictionary arguments to the format required by packevent by
replacing the keys, which are Python identifiers, by the four-character OSA keys according to the mapping
specified in keydict. Used by the generated suite packages.
enumsubst(arguments, key, edict)
If the arguments dictionary contains an entry for key convert the value for that entry according to
dictionary edict. This converts human-readable Python enumeration names to the OSA 4-character codes.
Used by the generated suite packages.
The aetools module defines the following class:
class TalkTo([signature=None, start=0, timeout=0 ])
Base class for the proxy used to talk to an application. signature overrides the class attribute
signature (which is usually set by subclasses) and is the 4-char creator code defining the applica-
tion to talk to. start can be set to true to enable running the application on class instantiation. timeout
can be specified to change the default timeout used while waiting for an AppleEvent reply.
start()
Test whether the application is running, and attempt to start it if not.
send(code, subcode[, parameters, attributes ])
Create the AppleEvent Carbon.AE.AEDesc for the verb with the OSA designation code, subcode
(which are the usual 4-character strings), pack the parameters and attributes into it, send it to the
target application, wait for the reply, unpack the reply with unpackevent and return the reply appleevent,
the unpacked return values as a dictionary and the return attributes.

3.3 aepack — Conversion between Python variables and AppleEvent


data containers
The aepack module defines functions for converting (packing) Python variables to AppleEvent descriptors
and back (unpacking). Within Python the AppleEvent descriptor is handled by Python objects of built-in type
AEDesc, defined in module Carbon.AE.
The aepack module defines the following functions:
pack(x[, forcetype ])
Returns an AEDesc object containing a conversion of Python value x. If forcetype is provided it specifies

3.2. aetools — OSA client support 23


the descriptor type of the result. Otherwise, a default mapping of Python types to Apple Event descriptor
types is used, as follows:
Python type descriptor type
FSSpec typeFSS
FSRef typeFSRef
Alias typeAlias
integer typeLong (32 bit integer)
float typeFloat (64 bit floating point)
string typeText
unicode typeUnicodeText
list typeAEList
dictionary typeAERecord
instance see below
If x is a Python instance then this function attempts to call an aepack () method. This method
should return an AEDesc object.
If the conversion x is not defined above, this function returns the Python string representation of a value (the
repr() function) encoded as a text descriptor.
unpack(x[, formodulename ])
x must be an object of type AEDesc. This function returns a Python object representation of the data
in the Apple Event descriptor x. Simple AppleEvent data types (integer, text, float) are returned as their
obvious Python counterparts. Apple Event lists are returned as Python lists, and the list elements are re-
cursively unpacked. Object references (ex. line 3 of document 1) are returned as instances of
aetypes.ObjectSpecifier, unless formodulename is specified. AppleEvent descriptors with
descriptor type typeFSS are returned as FSSpec objects. AppleEvent record descriptors are returned as
Python dictionaries, with 4-character string keys and elements recursively unpacked.
The optional formodulename argument is used by the stub packages generated by gensuitemodule,
and ensures that the OSA classes for object specifiers are looked up in the correct module. This ensures that
if, say, the Finder returns an object specifier for a window you get an instance of Finder.Window and
not a generic aetypes.Window. The former knows about all the properties and elements a window has
in the Finder, while the latter knows no such things.
See Also:
Module Carbon.AE (section 4.1):
Built-in access to Apple Event Manager routines.
Module aetypes (section 3.4):
Python definitions of codes for Apple Event descriptor types.
Inside Macintosh: Interapplication Communication
(http://developer.apple.com/techpubs/mac/IAC/IAC-2.html)
Information about inter-process communications on the Macintosh.

3.4 aetypes — AppleEvent objects


The aetypes defines classes used to represent Apple Event data descriptors and Apple Event object specifiers.
Apple Event data is contained in descriptors, and these descriptors are typed. For many descriptors the Python
representation is simply the corresponding Python type: typeText in OSA is a Python string, typeFloat
is a float, etc. For OSA types that have no direct Python counterpart this module declares classes. Packing and
unpacking instances of these classes is handled automatically by aepack.
An object specifier is essentially an address of an object implemented in a Apple Event server. An Apple Event
specifier is used as the direct object for an Apple Event or as the argument of an optional parameter. The aetypes
module contains the base classes for OSA classes and properties, which are used by the packages generated by
gensuitemodule to populate the classes and properties in a given suite.
For reasons of backward compatibility, and for cases where you need to script an application for which you have
not generated the stub package this module also contains object specifiers for a number of common OSA classes

24 Chapter 3. MacPython OSA Modules


such as Document, Window, Character, etc.
The AEObjects module defines the following classes to represent Apple Event descriptor data:
class Unknown(type, data)
The representation of OSA descriptor data for which the aepack and aetypes modules have no support,
i.e. anything that is not represented by the other classes here and that is not equivalent to a simple Python
value.
class Enum(enum)
An enumeration value with the given 4-character string value.
class InsertionLoc(of, pos)
Position pos in object of.
class Boolean(bool)
A boolean.
class StyledText(style, text)
Text with style information (font, face, etc) included.
class AEText(script, style, text)
Text with script system and style information included.
class IntlText(script, language, text)
Text with script system and language information included.
class IntlWritingCode(script, language)
Script system and language information.
class QDPoint(v, h)
A quickdraw point.
class QDRectangle(v0, h0, v1, h1)
A quickdraw rectangle.
class RGBColor(r, g, b)
A color.
class Type(type)
An OSA type value with the given 4-character name.
class Keyword(name)
An OSA keyword with the given 4-character name.
class Range(start, stop)
A range.
class Ordinal(abso)
Non-numeric absolute positions, such as "firs", first, or "midd", middle.
class Logical(logc, term)
The logical expression of applying operator logc to term.
class Comparison(obj1, relo, obj2)
The comparison relo of obj1 to obj2.
The following classes are used as base classes by the generated stub packages to represent AppleScript classes
and properties in Python:
class ComponentItem(which[, fr ])
Abstract baseclass for an OSA class. The subclass should set the class attribute want to the 4-character
OSA class code. Instances of subclasses of this class are equivalent to AppleScript Object Specifiers. Upon
instantiation you should pass a selector in which, and optionally a parent object in fr.
class NProperty(fr)
Abstract basclass for an OSA property. The subclass should set the class attributes want and which to
designate which property we are talking about. Instances of subclasses of this class are Object Specifiers.
class ObjectSpecifier(want, form, seld[, fr ])

3.4. aetypes — AppleEvent objects 25


Base class of ComponentItem and NProperty, a general OSA Object Specifier. See the Apple Open
Scripting Architecture documentation for the parameters. Note that this class is not abstract.

3.5 MiniAEFrame — Open Scripting Architecture server support


The module MiniAEFrame provides a framework for an application that can function as an Open Scripting
Architecture (OSA) server, i.e. receive and process AppleEvents. It can be used in conjunction with FrameWork
or standalone. As an example, it is used in PythonCGISlave.
The MiniAEFrame module defines the following classes:
class AEServer()
A class that handles AppleEvent dispatch. Your application should subclass this class together with ei-
ther MiniApplication or FrameWork.Application. Your init () method should call the
init () method for both classes.
class MiniApplication()
A class that is more or less compatible with FrameWork.Application but with less functionality. Its
event loop supports the apple menu, command-dot and AppleEvents; other events are passed on to the
Python interpreter and/or Sioux. Useful if your application wants to use AEServer but does not provide
its own windows, etc.

3.5.1 AEServer Objects


installaehandler(classe, type, callback)
Installs an AppleEvent handler. classe and type are the four-character OSA Class and Type designators,
’****’ wildcards are allowed. When a matching AppleEvent is received the parameters are decoded and
your callback is invoked.
callback( object, **kwargs)
Your callback is called with the OSA Direct Object as first positional parameter. The other parameters are
passed as keyword arguments, with the 4-character designator as name. Three extra keyword parameters
are passed: class and type are the Class and Type designators and attributes is a dictionary
with the AppleEvent attributes.
The return value of your method is packed with aetools.packevent() and sent as reply.
Note that there are some serious problems with the current design. AppleEvents which have non-identifier 4-
character designators for arguments are not implementable, and it is not possible to return an error to the originator.
This will be addressed in a future release.

26 Chapter 3. MacPython OSA Modules


CHAPTER

FOUR

MacOS Toolbox Modules

There are a set of modules that provide interfaces to various MacOS toolboxes. If applicable the module will define
a number of Python objects for the various structures declared by the toolbox, and operations will be implemented
as methods of the object. Other operations will be implemented as functions in the module. Not all operations
possible in C will also be possible in Python (callbacks are often a problem), and parameters will occasionally
be different in Python (input and output buffers, especially). All methods and functions have a doc string
describing their arguments and return values, and for additional description you are referred to Inside Macintosh
or similar works.
These modules all live in a package called Carbon. Despite that name they are not all part of the Carbon
framework: CF is really in the CoreFoundation framework and Qt is in the QuickTime framework. The normal
use pattern is
from Carbon import AE

Warning! These modules are not yet documented. If you wish to contribute documentation of any of these
modules, please get in touch with [email protected].
Carbon.AE Interface to the Apple Events toolbox.
Carbon.AH Interface to the Apple Help manager.
Carbon.App Interface to the Appearance Manager.
Carbon.CF Interface to the Core Foundation.
Carbon.CG Interface to the Component Manager.
Carbon.CaronEvt Interface to the Carbon Event Manager.
Carbon.Cm Interface to the Component Manager.
Carbon.Ctl Interface to the Control Manager.
Carbon.Dlg Interface to the Dialog Manager.
Carbon.Evt Interface to the classic Event Manager.
Carbon.Fm Interface to the Font Manager.
Carbon.Folder Interface to the Folder Manager.
Carbon.Help Interface to the Carbon Help Manager.
Carbon.List Interface to the List Manager.
Carbon.Menu Interface to the Menu Manager.
Carbon.Mlte Interface to the MultiLingual Text Editor.
Carbon.Qd Interface to the QuickDraw toolbox.
Carbon.Qdoffs Interface to the QuickDraw Offscreen APIs.
Carbon.Qt Interface to the QuickTime toolbox.
Carbon.Res Interface to the Resource Manager and Handles.
Carbon.Scrap Interface to the Carbon Scrap Manager.
Carbon.Snd Interface to the Sound Manager.
Carbon.TE Interface to TextEdit.
Carbon.Win Interface to the Window Manager.
ColorPicker Interface to the standard color selection dialog.

27
4.1 Carbon.AE — Apple Events

4.2 Carbon.AH — Apple Help

4.3 Carbon.App — Appearance Manager

4.4 Carbon.CF — Core Foundation


The CFBase, CFArray, CFData, CFDictionary, CFString and CFURL objects are supported, some only
partially.

28 Chapter 4. MacOS Toolbox Modules


4.5 Carbon.CG — Core Graphics

4.6 Carbon.CarbonEvt — Carbon Event Manager

4.7 Carbon.Cm — Component Manager

4.8 Carbon.Ctl — Control Manager

4.9 Carbon.Dlg — Dialog Manager

4.10 Carbon.Evt — Event Manager

4.11 Carbon.Fm — Font Manager

4.12 Carbon.Folder — Folder Manager

4.13 Carbon.Help — Help Manager

4.14 Carbon.List — List Manager

4.15 Carbon.Menu — Menu Manager

4.16 Carbon.Mlte — MultiLingual Text Editor

4.17 Carbon.Qd — QuickDraw

4.18 Carbon.Qdoffs — QuickDraw Offscreen

4.19 Carbon.Qt — QuickTime

4.20 Carbon.Res — Resource Manager and Handles

4.21 Carbon.Scrap — Scrap Manager

4.22 Carbon.Snd — Sound Manager

4.23 Carbon.TE — TextEdit

4.24 Carbon.Win — Window Manager

4.25 ColorPicker — Color selection dialog

4.5. Carbon.CG — Core Graphics 29


The ColorPicker module provides access to the standard color picker dialog.
GetColor(prompt, rgb)
Show a standard color selection dialog and allow the user to select a color. The user is given instruction by
the prompt string, and the default color is set to rgb. rgb must be a tuple giving the red, green, and blue
components of the color. GetColor() returns a tuple giving the user’s selected color and a flag indicating
whether they accepted the selection of cancelled.

30 Chapter 4. MacOS Toolbox Modules


CHAPTER

FIVE

Undocumented Modules

The modules in this chapter are poorly documented (if at all). If you wish to contribute documentation of any of
these modules, please get in touch with [email protected].
applesingle Rudimentary decoder for AppleSingle format files.
buildtools Helper module for BuildApplet, BuildApplication and macfreeze.
py resource Helper to create ’PYC ’ resources for compiled applications.
cfmfile Code Fragment Resource module.
icopen Internet Config replacement for open().
macerrors Constant definitions for many Mac OS error codes.
macresource Locate script resources.
Nac Interface to Navigation Services.
mkcwproject Create CodeWarrior projects.
nsremote Wrapper around Netscape OSA modules.
PixMapWrapper Wrapper for PixMap objects.
preferences Nice application preferences manager with support for defaults.
pythonprefs Specialized preferences manager for the Python interpreter.
quietconsole Buffered, non-visible standard output.
videoreader Read QuickTime movies frame by frame for further processing.
W Widgets for the Mac, built on top of FrameWork.
waste Interface to the “WorldScript-Aware Styled Text Engine.”

5.1 applesingle — AppleSingle decoder

5.2 buildtools — Helper module for BuildApplet and Friends

5.3 py resource — Resources from Python code


This module is primarily used as a help module for BuildApplet and BuildApplication. It is able to store compiled
Python code as ’PYC ’ resources in a file.

5.4 cfmfile — Code Fragment Resource module


cfmfile is a module that understands Code Fragments and the accompanying “cfrg” resources. It can parse
them and merge them, and is used by BuildApplication to combine all plugin modules to a single executable.

5.5 icopen — Internet Config replacement for open()


Importing icopen will replace the builtin open() with a version that uses Internet Config to set file type and
creator for new files.

31
5.6 macerrors — Mac OS Errors
macerrors cotains constant definitions for many Mac OS error codes.

5.7 macresource — Locate script resources


macresource helps scripts finding their resources, such as dialogs and menus, without requiring special case
code for when the script is run under MacPython, as a MacPython applet or under OSX Python.

5.8 Nav — NavServices calls


A low-level interface to Navigation Services.

5.9 mkcwproject — Create CodeWarrior projects


mkcwproject creates project files for the Metrowerks CodeWarrior development environment. It is a helper
module for distutils but can be used separately for more control.

5.10 nsremote — Wrapper around Netscape OSA modules


nsremote is a wrapper around the Netscape OSA modules that allows you to easily send your browser to a given
URL. A related module that may be of interest is the webbrowser module, documented in the Python Library
Reference.

5.11 PixMapWrapper — Wrapper for PixMap objects


PixMapWrapper wraps a PixMap object with a Python object that allows access to the fields by name. It also
has methods to convert to and from PIL images.

5.12 preferences — Application preferences manager


The preferences module allows storage of user preferences in the system-wide preferences folder, with de-
faults coming from the application itself and the possibility to override preferences for specific situations.

5.13 pythonprefs — Preferences manager for Python


This module is a specialization of the preferences module that allows reading and writing of the preferences
for the Python interpreter.

5.14 quietconsole — Non-visible standard output


quietconsole allows you to keep stdio output in a buffer without displaying it (or without displaying the
stdout window altogether, if set with EditPythonPrefs) until you try to read from stdin or disable the buffering,
at which point all the saved output is sent to the window. Good for programs with graphical user interfaces that
do want to display their output at a crash.

32 Chapter 5. Undocumented Modules


5.15 videoreader — Read QuickTime movies
videoreader reads and decodes QuickTime movies and passes a stream of images to your program. It also
provides some support for audio tracks.

5.16 W — Widgets built on FrameWork


The W widgets are used extensively in the IDE.

5.17 waste — non-Apple TextEdit replacement


See Also:
About WASTE
(http://www.merzwaren.com/waste/)
Information about the WASTE widget and library, including documentation and downloads.

5.15. videoreader — Read QuickTime movies 33


34
APPENDIX

History and License

A.1 History of the software


Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see
http://www.cwi.nl/) in the Netherlands as a successor of a language called ABC. Guido remains Python’s principal
author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see
http://www.cnri.reston.va.us/) in Reston, Virginia where he released several versions of the software.
In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen Python-
Labs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation;
see http://www.zope.com/). In 2001, the Python Software Foundation (PSF, see http://www.python.org/psf/) was
formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corpora-
tion is a sponsoring member of the PSF.
All Python releases are Open Source (see http://www.opensource.org/ for the Open Source Definition). Histori-
cally, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various
releases.

Release Derived from Year Owner GPL compatible?


0.9.0 thru 1.2 n/a 1991-1995 CWI yes
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI no
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF yes
2.1.1 2.1+2.0.1 2001 PSF yes
2.2 2.1.1 2001 PSF yes
2.1.2 2.1.1 2002 PSF yes
2.1.3 2.1.2 2002 PSF yes
2.2.1 2.2 2002 PSF yes
2.2.2 2.2.1 2002 PSF yes
2.2.3 2.2.2 2002-2003 PSF yes
2.3 2.2.2 2002-2003 PSF yes
2.3.1 2.3 2002-2003 PSF yes
2.3.2 2.3.1 2003 PSF yes
2.3.3 2.3.2 2003 PSF yes
2.3.4 2.3.3 2004 PSF yes

Note: GPL-compatible doesn’t mean that we’re distributing Python under the GPL. All Python licenses, unlike
the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible
licenses make it possible to combine Python with other software that is released under the GPL; the others don’t.
Thanks to the many outside volunteers who have worked under Guido’s direction to make these releases possible.

35
A.2 Terms and conditions for accessing or otherwise using Python
PSF LICENSE AGREEMENT FOR PYTHON 2.3.4
1. This LICENSE AGREEMENT is between the Python Software Foundation (“PSF”), and the Individual or
Organization (“Licensee”) accessing and otherwise using Python 2.3.4 software in source or binary form
and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare deriva-
tive works, distribute, and otherwise use Python 2.3.4 alone or in any derivative version, provided, however,
that PSF’s License Agreement and PSF’s notice of copyright, i.e., “Copyright c 2001-2003 Python Soft-
ware Foundation; All Rights Reserved” are retained in Python 2.3.4 alone or in any derivative version
prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on or incorporates Python 2.3.4 or any part
thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby
agrees to include in any such work a brief summary of the changes made to Python 2.3.4.
4. PSF is making Python 2.3.4 available to Licensee on an “AS IS” basis. PSF MAKES NO REPRESEN-
TATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMI-
TATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MER-
CHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON
2.3.4 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.3.4 FOR ANY
INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFY-
ING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3.4, OR ANY DERIVATIVE THEREOF,
EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or
joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or
any third party.
8. By copying, installing or otherwise using Python 2.3.4, Licensee agrees to be bound by the terms and
conditions of this License Agreement.

BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0


BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1

1. This LICENSE AGREEMENT is between BeOpen.com (“BeOpen”), having an office at 160 Saratoga
Avenue, Santa Clara, CA 95051, and the Individual or Organization (“Licensee”) accessing and otherwise
using this software in source or binary form and its associated documentation (“the Software”).
2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Li-
censee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display
publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative
version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any
derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an “AS IS” basis. BEOPEN MAKES NO REP-
RESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT
LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT
OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF,
EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

36 Appendix A. History and License


5. This License Agreement will automatically terminate upon a material breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of
California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License
Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to
endorse or promote products or services of Licensee, or any third party. As an exception, the “BeOpen
Python” logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions
granted on that web page.
7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and
conditions of this License Agreement.

CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1

1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an
office at 1895 Preston White Drive, Reston, VA 20191 (“CNRI”), and the Individual or Organization (“Li-
censee”) accessing and otherwise using Python 1.6.1 software in source or binary form and its associated
documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclu-
sive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare
derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided,
however, that CNRI’s License Agreement and CNRI’s notice of copyright, i.e., “Copyright c 1995-2001
Corporation for National Research Initiatives; All Rights Reserved” are retained in Python 1.6.1 alone
or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI’s License Agreement,
Licensee may substitute the following text (omitting the quotes): “Python 1.6.1 is made available sub-
ject to the terms and conditions in CNRI’s License Agreement. This Agreement together with Python
1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle):
1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following
URL: http://hdl.handle.net/1895.22/1013.”
3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part
thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby
agrees to include in any such work a brief summary of the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an “AS IS” basis. CNRI MAKES NO REPRESEN-
TATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMI-
TATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MER-
CHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON
1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY
INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFY-
ING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF,
EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach of its terms and conditions.
7. This License Agreement shall be governed by the federal intellectual property law of the United States, in-
cluding without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply,
by the law of the Commonwealth of Virginia, excluding Virginia’s conflict of law provisions. Notwithstand-
ing the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable
material that was previously distributed under the GNU General Public License (GPL), the law of the Com-
monwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect
to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License
Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse
or promote products or services of Licensee, or any third party.
8. By clicking on the “ACCEPT” button where indicated, or by copying, installing or otherwise using Python
1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement.

A.2. Terms and conditions for accessing or otherwise using Python 37


ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
Copyright
c 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee
is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice
and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific,
written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TOR-
TIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

38 Appendix A. History and License


MODULE INDEX

A G
aepack, 23 gensuitemodule, 22
aetools, 23
aetypes, 24 I
applesingle, 31 ic, 10
autoGIL, 19 icopen, 31

B M
buildtools, 31 mac, 7
macerrors, 32
C macfs, 7
Carbon.AE, 28 MacOS, 11
Carbon.AH, 28 macostools, 13
Carbon.App, 28 macpath, 7
Carbon.CaronEvt, 29 macresource, 32
Carbon.CF, 28 MiniAEFrame, 26
Carbon.CG, 29 mkcwproject, 32
Carbon.Cm, 29
Carbon.Ctl, 29 N
Carbon.Dlg, 29 Nac, 32
Carbon.Evt, 29 nsremote, 32
Carbon.Fm, 29
Carbon.Folder, 29 P
Carbon.Help, 29 PixMapWrapper, 32
Carbon.List, 29 preferences, 32
Carbon.Menu, 29 py resource, 31
Carbon.Mlte, 29 pythonprefs, 32
Carbon.Qd, 29
Carbon.Qdoffs, 29 Q
Carbon.Qt, 29 quietconsole, 32
Carbon.Res, 29
Carbon.Scrap, 29 V
Carbon.Snd, 29 videoreader, 33
Carbon.TE, 29
Carbon.Win, 29 W
cfmfile, 31 W, 33
ColorPicker, 29 waste, 33
E
EasyDialogs, 14

F
findertools, 13
FrameWork, 16

39
40
INDEX

Symbols Carbon.Evt (standard module), 29


quit() (Application method), 17 Carbon.Fm (standard module), 29
start() (TalkTo method), 23 Carbon.Folder (standard module), 29
Carbon.Help (standard module), 29
A Carbon.List (standard module), 29
Carbon.Menu (standard module), 29
aepack (standard module), 23
Carbon.Mlte (standard module), 29
AEServer (class in MiniAEFrame), 26
Carbon.Qd (built-in module), 29
AEText (class in aetypes), 25
Carbon.Qdoffs (built-in module), 29
aetools (standard module), 23
Carbon.Qt (standard module), 29
aetypes (standard module), 24
Carbon.Res (standard module), 29
Alias Manager, Macintosh, 7
Carbon.Scrap (standard module), 29
AppleEvents, 13, 26
Carbon.Snd (standard module), 29
applesingle (standard module), 31
Carbon.TE (standard module), 29
Application() (in module FrameWork), 16
Carbon.Win (standard module), 29
as pathname() (FSSpec method), 9
cfmfile (standard module), 31
as tuple() (FSSpec method), 9
close() (Window method), 18
AskFileForOpen() (in module EasyDialogs),
ColorPicker (extension module), 29
15
Comparison (class in aetypes), 25
AskFileForSave() (in module EasyDialogs),
ComponentItem (class in aetypes), 25
15
copy()
AskFolder() (in module EasyDialogs), 15
in module findertools, 13
AskPassword() (in module EasyDialogs), 14
in module macostools, 13
AskString() (in module EasyDialogs), 14
copytree() (in module macostools), 13
AskYesNoCancel() (in module EasyDialogs),
Creator (FInfo attribute), 9
14
curval (ProgressBar attribute), 15
asyncevents() (Application method), 17
autoGIL (extension module), 19
AutoGILError (exception in autoGIL), 19
D
data
B Alias attribute, 9
FSSpec attribute, 9
Boolean (class in aetypes), 25
DebugStr() (in module MacOS), 12
BUFSIZ (data in macostools), 13
DialogWindow() (in module FrameWork), 16
buildtools (standard module), 31
distutils (built-in module), 32
C do activate()
method, 18
callback() (AEServer method), 26 ScrolledWindow method, 18
Carbon.AE (standard module), 28 do char() (Application method), 17
Carbon.AH (standard module), 28 do contentclick() (Window method), 18
Carbon.App (standard module), 28 do controlhit()
Carbon.CaronEvt (standard module), 29 ControlsWindow method, 18
Carbon.CF (standard module), 28 ScrolledWindow method, 19
Carbon.CG (standard module), 29 do dialogevent() (Application method), 17
Carbon.Cm (standard module), 29 do itemhit() (DialogWindow method), 19
Carbon.Ctl (standard module), 29 do postresize()
Carbon.Dlg (standard module), 29 ScrolledWindow method, 19

41
Window method, 18 K
do update() (Window method), 18 keysubst() (in module aetools), 23
Keyword (class in aetypes), 25
E
EasyDialogs (standard module), 14 L
Enum (class in aetypes), 25 label() (ProgressBar method), 15
enumsubst() (in module aetools), 23 launch() (in module findertools), 13
environment variables launchurl()
PYTHONPATH, 2 IC method, 10
Error (exception in MacOS), 11 in module ic, 10
error (exception in ic), 10 linkmodel (data in MacOS), 11
Location (FInfo attribute), 10
F Logical (class in aetypes), 25
FindApplication() (in module macfs), 8
findertools (standard module), 13 M
FindFolder() (in module macfs), 8 mac (built-in module), 7
FInfo() (in module macfs), 8 macerrors (standard module), 11, 32
Flags (FInfo attribute), 10 macfs (standard module), 7
Fldr (FInfo attribute), 10 Macintosh Alias Manager, 7
FrameWork (standard module), 16, 26 MacOS (built-in module), 11
FSSpec() (in module macfs), 8 macostools (standard module), 13
macpath (standard module), 7
G macresource (standard module), 32
gensuitemodule (standard module), 22 mainloop() (Application method), 17
getabouttext() (Application method), 17 makeusermenus() (Application method), 17
GetArgv() (in module EasyDialogs), 14 mapfile()
GetColor() (in module ColorPicker), 30 IC method, 11
GetCreatorAndType() (in module MacOS), in module ic, 10
12 maptypecreator()
GetCreatorType() (FSSpec method), 9 IC method, 11
GetDates() (FSSpec method), 9 in module ic, 10
GetDirectory() (in module macfs), 8 maxval (ProgressBar attribute), 15
GetErrorString() (in module MacOS), 12 Menu() (in module FrameWork), 16
GetFInfo() (FSSpec method), 9 MenuBar() (in module FrameWork), 16
GetInfo() (Alias method), 9 MenuItem() (in module FrameWork), 16
getscrollbarvalues() (ScrolledWindow Message() (in module EasyDialogs), 14
method), 18 MiniAEFrame (standard module), 26
GetTicks() (in module MacOS), 12 MiniApplication (class in MiniAEFrame), 26
mkalias() (in module macostools), 13
H mkcwproject (standard module), 32
HandleEvent() (in module MacOS), 12 move() (in module findertools), 13

I N
IC (class in ic), 10 Nac (standard module), 32
ic (built-in module), 10 NewAlias() (FSSpec method), 9
icglue (built-in module), 10 NewAliasMinimal() (FSSpec method), 9
icopen (standard module), 31 NewAliasMinimalFromFullPath() (in
idle() (Application method), 17 module macfs), 8
inc() (ProgressBar method), 15 NProperty (class in aetypes), 25
InsertionLoc (class in aetypes), 25 nsremote (standard module), 32
installaehandler() (AEServer method), 26
installAutoGIL() (in module autoGIL), 19 O
Internet Config, 10 ObjectSpecifier (class in aetypes), 25
IntlText (class in aetypes), 25 open()
IntlWritingCode (class in aetypes), 25 DialogWindow method, 19
is scriptable() (in module gensuitemodule), Window method, 18
22 Open Scripting Architecture, 26

42 Index
openrf() (in module MacOS), 12 in module ic, 10
Ordinal (class in aetypes), 25 setwatchcursor() (in module FrameWork), 17
os (standard module), 7 shutdown() (in module findertools), 14
os.path (standard module), 7 sleep() (in module findertools), 13
splash() (in module MacOS), 12
P Standard File, 7
pack() (in module aepack), 23 StandardGetFile() (in module macfs), 8
packevent() (in module aetools), 23 StandardPutFile() (in module macfs), 8
parseurl() StyledText (class in aetypes), 25
IC method, 11 SubMenu() (in module FrameWork), 16
in module ic, 10 SysBeep() (in module MacOS), 12
PixMapWrapper (standard module), 32
preferences (standard module), 32 T
Print() (in module findertools), 13 TalkTo (class in aetools), 23
processfile() (in module gensuitemodule), 22 title() (ProgressBar method), 15
processfile fromresource() (in module touched() (in module macostools), 13
gensuitemodule), 22 Type
ProgressBar() (in module EasyDialogs), 14 class in aetypes, 25
PromptGetFile() (in module macfs), 8 FInfo attribute, 10
py resource (standard module), 31
PYTHONPATH, 2 U
pythonprefs (standard module), 32 Unknown (class in aetypes), 25
unpack() (in module aepack), 24
Q unpackevent() (in module aetools), 23
QDPoint (class in aetypes), 25 Update() (Alias method), 9
QDRectangle (class in aetypes), 25 updatescrollbars() (ScrolledWindow
quietconsole (standard module), 32 method), 18

R V
Range (class in aetypes), 25 videoreader (standard module), 33
RawAlias() (in module macfs), 8
RawFSSpec() (in module macfs), 8 W
Resolve() (Alias method), 9 W (standard module), 33
ResolveAliasFile() (in module macfs), 8 waste (standard module), 33
restart() (in module findertools), 13 Window() (in module FrameWork), 16
RGBColor (class in aetypes), 25 windowbounds() (in module FrameWork), 16
runtimemodel (data in MacOS), 11 WMAvailable() (in module MacOS), 12

S
scalebarvalues() (ScrolledWindow method),
18
SchedParams() (in module MacOS), 12
scrollbar callback() (ScrolledWindow
method), 18
scrollbars() (ScrolledWindow method), 18
send() (TalkTo method), 23
Separator() (in module FrameWork), 16
set() (ProgressBar method), 15
setarrowcursor() (in module FrameWork), 17
SetCreatorAndType() (in module MacOS),
12
SetCreatorType() (FSSpec method), 9
SetDates() (FSSpec method), 9
SetEventHandler() (in module MacOS), 11
SetFInfo() (FSSpec method), 9
SetFolder() (in module macfs), 8
settypecreator()
IC method, 11

Index 43

You might also like