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