3 <TITLE>Using Python
1.5 on the Macintosh
</TITLE>
6 <H1>Using Python
1.5 on the Macintosh
</H1>
9 This document is an introduction to using Python on the Apple
10 Macintosh. It does not introduce the language itself, for this you
11 should refer to the
<A
12 HREF=
"http://www.python.org/doc/tut/tut.html">Python Tutorial
</A> by
13 Guido van Rossum. This guide more-or-less replaces chapter two of the
14 tutorial, and provides some additional material.
<p>
16 The tutorial, along with other indispensible documentation like the
17 library reference and such, is also available in a number of different
18 formats at
<a href=
"ftp://ftp.python.org/pub/python/doc">
19 ftp://ftp.python.org/pub/python/doc
</a>. The Adobe Acrobat
<code>.pdf
</code>
20 files are probably a good choice for reading or printing the documents
23 There is currently no good tutorial for the mac-specific features of
24 Python, but to whet your appetite: it has interfaces to many MacOS
25 toolboxes (quickdraw, sound, quicktime, open scripting, etc) and
26 various portable toolboxes are available too (Tk, stdwin, complex
27 numbers, image manipulation, etc). Some
<A HREF=
"index.html">
28 annotated sample programs
</A> are available to give you an idea of
31 <h2>Invoking the interpreter
</h2>
33 The name of the interpreter may differ on different installations: it
34 may be called
<CODE>PythonFAT
</CODE> (for powerpc macs and
68K macs with
35 CFM68K installed) or
<CODE>Python68K
</CODE> (for
68K macs).
37 be recognizable by the
"16 ton" icon, though. You start the
38 interpreter in interactive mode by double-clicking its icon:
<p>
40 <img src=
"html.icons/python.gif"><p>
42 This should give you a text window with an informative version string
43 and a prompt, something like the following:
45 Python
1.5.1 (#
122 Aug
27,
1997) [CW PPC w/GUSI MSL]
46 Copyright
1991-
1997 Stichting Mathematisch Centrum, Amsterdam
49 The version string tells you the version of Python, whether it was
50 built for PPC or
68K macs and possibly some options used to build the
51 interpreter. If you find a bug or have a question about how the
52 interpreter works it is a good idea to include the version information
55 At the prompt you can type interactive python commands. See the
56 tutorial for more information. The interactive window works
57 more-or-less like a Communication Toolbox or Telnet window: you type
58 commands at the bottom and terminate them with the
<EM>[return]
</EM>
59 or
<EM>[enter]
</EM> key. Interpreter feedback also appears at the
60 bottom of the window, and the contents scroll as output is added. You
61 can use copy and paste in the normal way, but be sure to paste only at
62 the bottom of the document.
64 <h2>Creating Python scripts
</h2>
66 The Python interpreter works in a way that is different from what you
67 would expect of a macintosh program: the interpreter is just that: an
68 interpreter. There is no builtin editor or other development
69 support. Hence, to create a Python script you need an external text
70 editor. For a first script you can use any editor that can create
71 plain, unstyled text files, such as
<CODE>SimpleText
</CODE>.
<p>
73 For more serious scripts, though, it is advisable to use a programmers
74 editor, such as
<CODE>BBEdit
</CODE> or
<CODE>Alpha
</CODE>. BBEdit is
75 my favorite: it comes in a commercial version but also in a
76 fully-functional free version
<CODE>BBEdit Lite
</CODE>. You can
77 download it from the
<A HREF=
"http://www.barebones.com/">BareBones
</A>
78 site. The free version will probably provide all the functionality
79 you will ever need. Besides the standard edit facilities it has
80 multi-file searches and many other goodies that can be very handy when
83 After you have created your script in the editor of your choice you
84 drop it on the interpreter. This will start the interpreter executing
85 the script, again with a console window in which the output appears
86 and in which you can type input if the script requires it. Normally
87 the interpreter will close the window and quit as soon as the script
88 is done executing, see below under
<A HREF=
"#startup">startup
89 options
</A> for a way to change this.
<p>
92 There is a BBEdit extension available that allows you to run Python
93 scripts more-or-less straight from your bbedit source window. Check
94 out the
<code>Mac:Tools:BBPy
</code> folder.
97 It is a good idea to have the names of all your scripts end in
98 <CODE>.py
</CODE>. While this is not necessary for standalone scripts
99 it is needed for modules, and it is probably a good idea to start the
102 If you do not like to start the Python interpreter afresh for each
103 edit-run cycle you can use the
<CODE>import
</CODE> statement and
104 <CODE>reload()
</CODE> function to speed things up in some cases. Here
105 is Guido's original comment for how to do this, from the
1.1 release
110 Make sure the program is a module file (filename must be a Python
111 identifier followed by '
<CODE>.py
</CODE>'). You can then import it
112 when you test it for the first time. There are now three
113 possibilities: it contains a syntax error; it gets a runtime error
114 (unhandled exception); or it runs OK but gives wrong results. (If it
115 gives correct results, you are done testing and don't need to read the
116 rest of this paragraph. :-) Note that the following is not
117 Mac-specific -- it's just that on UNIX it's easier to restart the
118 entire script so it's rarely useful.
<P>
120 Recovery from a syntax error is easy: edit the file and import it
123 Recovery from wrong output is almost as easy: edit the file and,
124 instead of importing it, call the function
<CODE>reload()
</CODE> with
125 the module name as argument (e.g., if your module is called
126 <CODE>foo
</CODE>, type
<CODE>reload(foo)
</CODE>).
<P>
128 Recovery from an exception is trickier. Once the syntax is correct, a
129 'module' entry is placed in an internal table, and following import
130 statements will not re-read the file, even if the module's
131 initialization terminated with an error (one reason why this is done
132 is so that mutually recursive modules are initialized only once). You
133 must therefore force re-reading the module with
<CODE>reload()
</CODE>,
134 however, if this happens the first time you try to import the module,
135 the import statement itself has not completed, and your workspace does
136 not know the module name (even though the internal table of moduesl
137 does!). The trick is to first import the module again, then reload
138 it. For instance,
<CODE>import foo; reload(foo)
</CODE>. Because the
139 module object already exists internally, the import statement does not
140 attempt to execute the module again -- it just places it in your
141 workspace.
</BLOCKQUOTE>
143 <h2>Clickable python scripts
</h2>
145 If you create your script with the correct creator and type, creator
146 <CODE>'Pyth'
</CODE> and type
<CODE>'TEXT'
</CODE>, you can double-click
147 your script and it will automatically invoke the interpreter. If you
148 use BBEdit you can tell it about the Python file type by adding it to
149 the
"file types" sections of the preferences. Then, if you save a file
150 for the first time you can tell BBEdit to save the file as a Python
151 script through the
"options" choice of the save dialog.
<p>
153 The
<CODE>Scripts
</CODE> folder contains a script
154 <CODE>fixfiletypes
</CODE> that will recursively traverse a folder and
155 set the correct creator and type for all files ending in
156 <CODE>.py
</CODE>.
<p>
159 Older releases of Python used the creator code
160 <CODE>'PYTH'
</CODE> in stead of
<CODE>'Pyth'
</CODE>. If you still have
161 older Python sources on your system and named them with
162 <CODE>'.py'
</CODE> extension the
<CODE>fixfiletypes
</CODE> script will
166 <h2>Interaction with the user
</h2>
168 Normally, the interpreter will check for user input (mouse clicks,
169 keyboard input) every once in a while, so it is possible to switch to
170 other applications while a script runs. It is also possible to
171 interrupt the interpreter with the standard command-period keypress,
172 this will raise the
<CODE>KeyboardInterrupt
</CODE> exception. Scripts
173 may, however, turn off this behaviour to facilitate their own event
174 handling. Such scripts can only be killed with the
175 command-option-escape shortcut.
177 <h2><A NAME=
"startup">startup options
</A></h2>
179 If the
<EM>option
</EM> key is depressed when Python starts executing
180 the interpreter will bring up an options dialog thru which you can
181 influence the way the interpreter behaves. Keep the option key
182 depressed until the dialog comes up.
<p>
184 <img src=
"html.icons/options.gif"><p>
186 The options modify the interpreters behaviour in the following way:
188 <li> the interpreter goes to interactive mode (in stead of
189 exiting) after a script has terminated normally,
190 <li> for every module imported a line is printed telling you where the
191 module was loaded from,
192 <li> do not print the values of expressions executed as statements in
193 an interactive python (obsolete),
194 <li> do not buffer stdout and stderr,
195 <li> print some debugging output during the parsing phase,
196 <li> keep the output window open when a script terminates.
198 In addition, you can enter a unix-style command line which is passed
199 to the script in
<CODE>sys.argv
</CODE>. Sys.argv[
0] is always the name
200 of the script being executed, additional values can be passed
201 here. Quoting works as expected.
<p>
204 <EM>Warning:
</EM> redirecting standard input or standard output in the
205 command-line dialog does not work. This is due to circumstances beyond my
206 control, hence I cannot say when this will be fixed.
209 The default options are also settable on a system-wide basis, see the
210 section on
<A HREF=
"#preferences">editing preferences
</A>.
<p>
212 <h2>Module search path
</h2>
214 The module search path,
<CODE>sys.path
</CODE>, contains the folders
215 python will search when you import a module. The path is settable on a
216 system-wide basis (see the preferences section), and normally
217 comprises the current folder (where the script lives), the
218 <CODE>Lib
</CODE> folder and some of its subfolders and possibly some
221 <h2>Working folder
</h2>
223 The unix concept of a
<I>working directory
</I> does not translate
224 directly to a similar concept on the Macintosh. To facilitate easy
225 porting and the use of relative pathnames in scripts the interpreter
226 simulates a working directory. When a script is started the initial
227 working directory is the folder where the script lives. In case of an
228 interactive interpreter the working directory is the folder where the
229 interpreter lives.
<P>
231 By the way: the
"standard file" folder, the folder that is presented
232 to the user initially for an
<I>open
</I> or
<I>save
</I> dialog, does
233 <EM>not
</EM> follow the Python working directory. Which folder is
234 initially shown to the user is usually one of (a) the application
235 folder, (b) the
"Documents" folder or (c) the folder most recently
236 used for such a dialog (in any Python program). This is standard MacOS
237 behaviour, so don't blame Python for it. The exact behaviour is
238 settable through a control panel since System
7.5.
240 <h2>Interactive startup file
</h2>
242 If the folder containing the interpreter contains a file named
243 <CODE>PythonStartup
</CODE> this file is executed when you start an
244 interactive interpreter. In this file you could import modules you
245 often use and other such things.
<p>
248 <h2>Compiled python scripts
</h2>
250 Once a python module has been imported the interpreter creates a
251 compiled version which is stored in a file with the
".py" extension
252 replaced by
".pyc". These compiled files, with creator
253 <CODE>'Pyth'
</CODE> and type
<CODE>'PYC '
</CODE> load faster when
254 imported (because they do not have to be parsed). The
<CODE>Lib
</CODE>
255 folder contains a script
<CODE>compileall.py
</CODE>, running this
256 script will cause all modules along the python search path to be
257 precompiled, which will speed up your programs. Compiled files are
258 also double-clickable.
<p>
260 <h2>Python resources
</h2>
262 MacPython has the ability to collect a number of compiled modules
263 together in the resource fork of a single file. This feature is useful
264 if you distribute a python program and want to minimize clutter: you
265 can put all the needed modules in a single file (which could even be
266 the interpreter itself).
<p>
268 If the module search path contains a filename as one of its entries
269 (as opposed to a folder name, which is the normal case) this file will
270 be searched for a resource with type
<CODE>'PYC '
</CODE> and a name
271 matching the module being imported.
<p>
273 The
<CODE>scripts
</CODE> folder contains a script
274 <CODE>PackLibDir
</CODE> which will convert a number of modules (or
275 possibly a complete subtree full of modules) into such a resource
278 <h2><A NAME=
"preferences">Setting interpreter preferences
</A></h2>
280 The python interpreter keeps a preferences file in the standard
281 location in the system folder. In this preferences file it remembers
282 the default module search path and the default settings for the
283 runtime options. The preferences are settable via
284 <CODE>EditPythonPrefs
</CODE>. For PPC/cfm68k python this is a standalone
285 program living in the main Python folder, for
68K python it is a
286 script in the
<CODE>Mac:Scripts
</CODE> folder.
<p>
288 The interface to edit the preferences is rather clunky for the current
291 <img src=
"html.icons/preferences.gif"><p>
293 In the editable text field at the top you enter the initial module
294 search path, using newline as a separator. There are two special
295 values you can use here: an initial substring
<CODE>$(PYTHON)
</CODE>
296 will expand to the Python home folder and a value of
297 <CODE>$(APPLICATION)
</CODE> will expand to the the python application
298 itself. Note that the text field may extend
"beyond the bottom" even
299 though it does not have a scroll bar. Using the arrow keys works,
302 The Python home folder $(PYTHON) is initially, when you install Python,
303 set to the folder where the interpreter lives. You can change it here.
<p>
305 Finally, you can set the default startup options here, through a
310 An applet is a fullblown application written in Python, similar to an
311 AppleScript applet (and completely different from a Java
312 applet). Applets are currently supported on PowerPC macintoshes and on
313 68K macintoshes if you use the CFM68K version of the interpreter,
314 and are created using the
<CODE>BuildApplet
</CODE> program. You create an
315 applet by dropping the python source script onto BuildApplet.
316 <a href=
"example2.html">Example
2</a> is a more involved applet
317 with its own resource file, etc.
<p>
319 Note that while an applet behaves as a fullblown Macintosh application
320 it is not self-sufficient, so distributing it to a machine without an
321 installed Python interpreter will not work: it needs the shared python
322 execution engine
<CODE>PythonCore
</CODE>, and probably various modules
323 from the Lib and PlugIns folders. Distributing it to a machine that does
324 have a Python system will work.
<p>
326 <h2>Customizing applets
</h2>
328 Applets can have their own settings for the startup options and module
329 search path. Dropping an applet on the
<CODE>EditPythonPrefs
</CODE>
330 application allows you to set these, in the same way as
331 double-clicking EditPythonPrefs allows you to set the system-wide
334 Actually, not only applets but also the interpreter itself can have
335 non-default settings for path and options. If you make a copy of the
336 interpreter and drop this copy onto EditPythonPrefs you will have an
337 interpreter that has a different set of default settings.
<p>
339 <h2>Where to go from here
</h2>
341 The previously mentioned
<A
342 HREF=
"http://www.python.org/doc/tut/tut.html">Python Tutorial
</A> is
343 an excellent place to start reading if you have never used Python
344 before. Other documentation such as the library reference manual is
345 indexed at the
<A HREF=
"http://www.python.org/doc/">Python
346 Documentation
</A> page.
<p>
348 There are some
<A HREF=
"index.html">annotated sample programs
</A>
349 available that show some mac-specific issues, like use of various
350 toolboxes and creation of Python applets.
<p>
352 The
<CODE>Demo
</CODE> and
<CODE>Mac:Demo
</CODE>
353 folders in the Macintosh distribution
354 contains a number of other example programs. Most of these are only
355 very lightly documented, but they may help you to understand some
356 aspects of using Python.
<p>
358 Finally, there is a
<code>Mac:Contrib
</code> folder that contains
359 a few contributions to Python that I couldn't fit in the normal tree
360 but did want to distribute (many other contributions are contained
361 throughout the distribution, but you don't see them, really).
363 The best way to contact fellow Macintosh Python programmers is to join
364 the MacPython Special Interest Group mailing list. Send a message with
365 "info" in the body to
<A
366 HREF=
"mailto:pythonmac-sig-request@python.org">pythonmac-sig-request@python.org
</A>
368 HREF=
"http://www.python.org/sigs/pythonmac-sig/">Pythonmac SIG
369 page
</A> on the
<A HREF=
"http://www.python.org">www.python.org
</A> WWW
372 <h2>Troubleshooting
</h2>
374 A rather baffling error message can be
"PythonCore not found" when you
375 start the interpreter and you are sure that PythonCore is available. The
376 message should actually say
"Not enough memory in the system heap to
378 Blame Apple for the confusing message.
<p>
380 There appear to be problems with QuickTime for the CFM68K version of the
381 interpreter. If you experience these please contact the SIG: some people
382 use quicktime without problems and some not, and we are still hunting for
385 Python is a rather safe language, and hence it should be difficult to
386 crash the interpreter of the system with a Python script. There is an
387 exception to this rule, though: the modules that interface to the
388 system toolboxes (windowing, quickdraw, etc) do very little error
389 checking and therefore a misbehaving program using these modules may
390 indeed crash the system. Such programs are unfortunately rather
391 difficult to debug, since the crash does not generate the standard
392 Python stack trace, obviously, and since debugging print statements
393 will often interfere with the operation of the program. There is
394 little to do about this currently.
<p>
396 Probably the most common cause of problems with modules ported from
397 other systems is the Mac end-of-line convention. Where unix uses
398 linefeed,
0x0a, to separate lines the mac uses carriage return,
399 0x0d. To complicate matters more a lot of mac programming editors like
400 BBEdit and emacs will work happily with both conventions, so the file
401 will appear to be correct in the editor but cause strange errors when
402 imported. BBEdit has a popup menu which allows you to inspect (and
403 set) the end-of-line convention used in a file.
<p>
405 Python attempts to keep its preferences file up-to-date even when you
406 move the Python folder around, etc. If this fails the effect will be
407 that Python cannot start or, worse, that it does work but it cannot find
408 any standard modules. In this case, start Python and examine
<code>sys.path
</code>.
409 If it is incorrect remove any Python preferences file from the system
410 folder and start the interpreter
<em>while the interpreter sits in the main
411 Python folder
</em>. This will regenerate the preferences file. You may also
412 have to run the ConfigurePython applet again.
<p>
414 <h2>Your five minutes are up. Next!
</h2>
416 The next section to check out is the
<a href=
"index.html">annotated sample programs
</a>.
<p>
419 <A HREF=
"http://www.cwi.nl/~jack">Jack Jansen
</A>,
420 <A HREF=
"mailto:jack@cwi.nl">jack@cwi.nl
</A>,
27-Apr-
98.