blob: b12e6e14f570faab4db55c751bbeccbe44cc03d3 [file] [log] [blame]
Guido van Rossum515834a1991-01-22 11:45:29 +00001% Format this file with latex.
2
3%\documentstyle[palatino,11pt,myformat]{article}
4\documentstyle[11pt,myformat]{article}
5
6\sloppy
7
8\title{\bf
9 Python Library Reference \\
10 (DRAFT)
11}
12
13\author{
14 Guido van Rossum \\
15 Dept. CST, CWI, Kruislaan 413 \\
16 1098 SJ Amsterdam, The Netherlands \\
17 E-mail: {\tt guido@cwi.nl}
18}
19
20\begin{document}
21
22\pagenumbering{roman}
23
24\maketitle
25
26\begin{abstract}
27
28\noindent
29This document describes the built-in types, exceptions and functions and
30the standard modules that come with the {\Python} system.
31It assumes basic knowledge about the {\Python} language.
32For an informal introduction to the language, see the Tutorial document.
33The Language Reference document (XXX not yet existing)
34gives a more formal reference to the language.
35
36\end{abstract}
37
38\pagebreak
39
40\tableofcontents
41
42\pagebreak
43
44\pagenumbering{arabic}
45
46\section{Introduction}
47
48The {\Python} library consists of three parts, with different levels of
49integration with the interpreter.
50Closest to the interpreter are built-in types, exceptions and functions.
51Next are built-in modules, which are written in C and linked statically
52with the interpreter.
53Finally there are standard modules that are implemented entirely in
54{\Python}, but are always available.
55For efficiency, some standard modules may become built-in modules in
56future versions of the interpreter.
57
58\section{Built-in Types, Exceptions and Functions}
59
60Names for built-in exceptions and functions are found in a separate
61read-only symbol table which cannot be modified.
62This table is searched last, so local and global user-defined names can
63override built-in names.
64Built-in types have no names but are created by syntactic constructs
65(such as constants) or built-in functions.
66They are described together here for easy reference.%
67\footnote{
68The descriptions sorely lack explanations of the exceptions that
69may be raised---this will be fixed in a future version of this
70document.
71}
72
73\subsection{Built-in Types}
74
75The following sections describe the standard types that are built into the
76interpreter.
77\subsubsection{Numeric Types}
78
79There are two numeric types: integers and floating point numbers.
80Integers are implemented using {\tt long} in C, so they have at least 32
81bits of precision.
82Floating point numbers are implemented using {\tt double} in C.
83All bets on precision are off.
84Numbers are created by numeric constants or as the result of built-in
85functions and operators.
86
87Numeric types support the following operations:
88
89\begin{center}
90\begin{tabular}{|c|l|c|}
91\hline
92Operation & Result & Notes \\
93\hline
94{\tt abs}({\em x}) & absolute value of {\em x} & \\
95{\tt int}({\em x}) & {\em x} converted to integer & (1) \\
96{\tt float}({\em x}) & {\em x} converted to floating point & \\
97{\tt -}{\em x} & {\em x} negated & \\
98{\tt +}{\em x} & {\em x} unchanged & \\
99{\em x}{\tt +}{\em y} & sum of {\em x} and {\em y} & \\
100{\em x}{\tt -}{\em y} & difference of {\em x} and {\em y} & \\
101{\em x}{\tt *}{\em y} & product of {\em x} and {\em y} & \\
102{\em x}{\tt /}{\em y} & quotient of {\em x} and {\em y} & (2) \\
103{\em x}{\tt \%}{\em y} & remainder of {\em x}{\tt /}{\em y} & (3) \\
104\hline
105\end{tabular}
106\end{center}
107
108\noindent
109Notes:
110\begin{description}
111\item[(1)]
112This may round or truncate as in C; see functions {\tt floor} and
113{\tt ceil} in module {\tt math}.
114\item[(2)]
115Integer division is defined as in C: the result is an integer; with
116positive operands, it truncates towards zero; with a negative operand,
117the result is unspecified.
118\item[(3)]
119Only defined for integers.
120\end{description}
121
122Mixed arithmetic is not supported; both operands must have the same type.
123Mixed comparisons return the wrong result (floats always compare smaller
124than integers).%
125\footnote{
126These restrictions are bugs in the language definitions and will be
127fixed in the future.
128}
129\subsubsection{Sequence Types}
130
131There are three sequence types: strings, lists and tuples.
132Strings constants are written in single quotes: {\tt 'xyzzy'}.
133Lists are constructed with square brackets: {\tt [a,~b,~c]}.
134Tuples are constructed by the comma operator or with an empty set of
135parentheses: {\tt a,~b,~c} or {\tt ()}.
136
137Sequence types support the following operations ({\em s} and {\em t} are
138sequences of the same type; {\em n}, {\em i} and {\em j} are integers):
139
140\begin{center}
141\begin{tabular}{|c|l|c|}
142\hline
143Operation & Result & Notes \\
144\hline
145{\tt len}({\em s}) & length of {\em s} & \\
146{\tt min}({\em s}) & smallest item of {\em s} & \\
147{\tt max}({\em s}) & largest item of {\em s} & \\
148{\em x} {\tt in} {\em s} &
149 true if an item of {\em s} is equal to {\em x} & \\
150{\em x} {\tt not} {\tt in} {\em s} &
151 false if an item of {\em s} is equal to {\em x} & \\
152{\em s}{\tt +}{\em t} & the concatenation of {\em s} and {\em t} & \\
153{\em s}{\tt *}{\em n}, {\em n}*{\em s} &
154 {\em n} copies of {\em s} concatenated & (1) \\
155{\em s}[{\em i}] & {\em i}'th item of {\em s} & \\
156{\em s}[{\em i}:{\em j}] &
157 slice of {\em s} from {\em i} to {\em j} & (2) \\
158\hline
159\end{tabular}
160\end{center}
161
162\noindent
163Notes:
164\begin{description}
165\item[(1)]
166Sequence repetition is only supported for strings.
167\item[(2)]
168The slice of $s$ from $i$ to $j$ is defined as the sequence
169of items with index $k$ such that $i \leq k < j$.
170Special rules apply for negative and omitted indices; see the Tutorial
171or the Reference Manual.
172\end{description}
173
174\paragraph{Mutable Sequence Types.}
175
176List objects support additional operations that allow in-place
177modification of the object.
178These operations would be supported by other mutable sequence types
179(when added to the language) as well.
180Strings and tuples are immutable sequence types and such objects cannot
181be modified once created.
182The following operations are defined on mutable sequence types (where
183{\em x} is an arbitrary object):
184
185\begin{center}
186\begin{tabular}{|c|l|}
187\hline
188Operation & Result \\
189\hline
190{\em s}[{\em i}] = {\em x} &
191 item {\em i} of {\em s} is replaced by {\em x} \\
192{\em s}[{\em i}:{\em j}] = {\em t} &
193 slice of {\em s} from {\em i} to {\em j} is replaced by {\em t} \\
194{\tt del} {\em s}[{\em i}:{\em j}] &
195 same as {\em s}[{\em i}:{\em j}] = [] \\
196{\em s}.{\tt append}({\em x}) &
197 same as {\em s}[{\tt len}({\em x}):{\tt len}({\em x})] = [{\em x}] \\
198{\em s}.{\tt insert}({\em i}, {\em x}) &
199 same as {\em s}[{\em i}:{\em i}] = [{\em x}] \\
200{\em s}.{\tt sort}() &
201 the items of {\em s} are permuted to satisfy \\
202 &
203 $s[i] \leq s[j]$ for $i < j$\\
204\hline
205\end{tabular}
206\end{center}
207
208\subsubsection{Mapping Types}
209
210A
211{\em mapping}
212object maps values of one type (the key type) to arbitrary objects.
213Mappings are mutable objects.
214There is currently only one mapping type, the
215{\em dictionary}.
216A dictionary's keys are strings.
217An empty dictionary is created by the expression \verb"{}".
218An extension of this notation is used to display dictionaries when
219written (see the example below).
220
221The following operations are defined on mappings (where {\em a} is a
222mapping, {\em k} is a key and {\em x} is an arbitrary object):
223
224\begin{center}
225\begin{tabular}{|c|l|c|}
226\hline
227Operation & Result & Notes\\
228\hline
229{\tt len}({\em a}) & the number of elements in {\em a} & \\
230{\em a}[{\em k}] & the item of {\em a} with key {\em k} & \\
231{\em a}[{\em k}] = {\em x} & set {\em a}[{\em k}] to {\em x} & \\
232{\tt del} {\em a}[{\em k}] & remove {\em a}[{\em k}] from {\em a} & \\
233{\em a}.{\tt keys}() & a copy of {\em a}'s list of keys & (1) \\
234{\em a}.{\tt has\_key}({\em k}) & true if {\em a} has a key {\em k} & \\
235\hline
236\end{tabular}
237\end{center}
238
239\noindent
240Notes:
241\begin{description}
242\item[(1)]
243Keys are listed in random order.
244\end{description}
245
246A small example using a dictionary:
247\begin{code}\begin{verbatim}
248>>> tel = {}
249>>> tel['jack'] = 4098
250>>> tel['sape'] = 4139
251>>> tel['guido'] = 4127
252>>> tel['jack']
2534098
254>>> tel
255{'sape': 4139; 'guido': 4127; 'jack': 4098}
256>>> del tel['sape']
257>>> tel['irv'] = 4127
258>>> tel
259{'guido': 4127; 'irv': 4127; 'jack': 4098}
260>>> tel.keys()
261['guido', 'irv', 'jack']
262>>> tel.has_key('guido')
2631
264>>>
265\end{verbatim}\end{code}
266\subsubsection{Other Built-in Types}
267
268The interpreter supports several other kinds of objects.
269Most of these support only one or two operations.
270
271\paragraph{Modules.}
272
273The only operation on a module is member acces: {\em m}{\tt .}{\em name},
274where {\em m} is a module and {\em name} accesses a name defined in
275{\em m}'s symbol table.
276Module members can be assigned to.
277
278\paragraph{Classes and Class Objects.}
279
280XXX Classes will be explained at length in a later version of this
281document.
282
283\paragraph{Functions.}
284
285Function objects are created by function definitions.
286The only operation on a function object is to call it:
287{\em func}({\em optional-arguments}).
288
289Built-in functions have a different type than user-defined functions,
290but they support the same operation.
291
292\paragraph{Methods.}
293
294Methods are functions that are called using the member acces notation.
295There are two flavors: built-in methods (such as {\tt append()} on
296lists) and class member methods.
297Built-in methods are described with the types that support them.
298XXX Class member methods will be described in a later version of this
299document.
300
301\paragraph{Type Objects.}
302
303Type objects represent the various object types.
304An object's type is accessed by the built-in function
305{\tt type()}.
306There are no operations on type objects.
307
308\paragraph{The Null Object.}
309
310This object is returned by functions that don't explicitly return a
311value.
312It supports no operations.
313There is exactly one null object.
314
315\paragraph{File Objects.}
316
317File objects are implemented using C's
318{\em stdio}
319package and can be created with the built-in function
320{\tt open()}.
321They have the following methods:
322\begin{description}
323\item[{\tt close()}]
324Closes the file.
325A closed file cannot be read or written anymore.
326\item[{\tt read(size)}]
327Reads at most
328{\tt size}
329bytes from the file (less if the read hits EOF).
330The bytes are returned as a string object.
331An empty string is returned when EOF is hit immediately.
332(For certain files, like ttys, it makes sense to continue reading after
333an EOF is hit.)
334\item[{\tt readline(size)}]
335Reads a line of at most
336{\tt size}
337bytes from the file.
338A trailing newline character, if present, is kept in the string.
339The size is optional and defaults to a large number (but not infinity).
340EOF is reported as by
341{\tt read().}
342\item[{\tt write(str)}]
343Writes a string to the file.
344Returns no value.
345\end{description}
346
347\subsection{Built-in Exceptions}
348
349The following exceptions can be generated by the interpreter or
350built-in functions.
351Except where mentioned, they have a string argument (also known as the
352`associated value' of an exception) indicating the detailed cause of the
353error.
354The strings listed with the exception names are their values when used
355in an expression or printed.
356\begin{description}
357\item[{\tt EOFError = 'end-of-file read'} (no argument)]
358%.br
359Raised when a built-in function ({\tt input()} or {\tt raw\_input()})
360hits an end-of-file condition (EOF) without reading any data.
361(N.B.: the {\tt read()} and {\tt readline()} methods of file objects
362return an empty string when they hit EOF.)
363\item[{\tt KeyboardInterrupt = 'end-of-file read'} (no argument)]
364%.br
365Raised when the user hits the interrupt key (normally Control-C or DEL).
366During execution, a check for interrupts is made regularly.
367Interrupts typed when a built-in function ({\tt input()} or
368{\tt raw\_input()}) is waiting for input also raise this exception.
369\item[{\tt MemoryError = 'out of memory'}]
370%.br
371Raised when an operation runs out of memory but the situation
372may still be rescued (by deleting some objects).
373\item[{\tt NameError = 'undefined name'}]
374%.br
375Raised when a name is not found.
376This applies to unqualified names, module names (on {\tt import}),
377module members and object methods.
378The string argument is the name that could not be found.
379\item[{\tt RuntimeError = 'run-time error'}]
380%.br
381Raised for a variety of reasons, e.g., division by zero or index out of
382range.
383\item[{\tt SystemError = 'system error'}]
384%.br
385Raised when the interpreter finds an internal error, but the situation
386does not look so serious to cause it to abandon all hope.
387\item[{\tt TypeError = 'type error'}]
388%.br
389Raised when an operation or built-in function is applied to an object of
390inappropriate type.
391\end{description}
392
393\subsection{Built-in Functions}
394
395The {\Python} interpreter has a small number of functions built into it that
396are always available.
397They are listed here in alphabetical order.
398\begin{description}
399\item[{\tt abs(x)}]
400Returns the absolute value of a number.
401The argument may be an integer or floating point number.
402\item[{\tt dir()}]
403Without arguments, this function returns the list of names in the
404current local symbol table, sorted alphabetically.
405With a module object as argument, it returns the sorted list of names in
406that module's global symbol table.
407For example:
408\begin{code}\begin{verbatim}
409>>> import sys
410>>> dir()
411['sys']
412>>> dir(sys)
413['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
414>>>
415\end{verbatim}\end{code}
416\item[{\tt divmod(a, b)}]
417%.br
418Takes two integers as arguments and returns a pair of integers
419consisting of their quotient and remainder.
420For
421\begin{code}\begin{verbatim}
422q, r = divmod(a, b)
423\end{verbatim}\end{code}
424the invariants are:
425\begin{code}\begin{verbatim}
426a = q*b + r
427abs(r) < abs(b)
428r has the same sign as b
429\end{verbatim}\end{code}
430For example:
431\begin{code}\begin{verbatim}
432>>> divmod(100, 7)
433(14, 2)
434>>> divmod(-100, 7)
435(-15, 5)
436>>> divmod(100, -7)
437(-15, -5)
438>>> divmod(-100, -7)
439(14, -2)
440>>>
441\end{verbatim}\end{code}
442\item[{\tt eval(s)}]
443Takes a string as argument and parses and evaluates it as a {\Python}
444expression.
445The expression is executed using the current local and global symbol
446tables.
447Syntax errors are reported as exceptions.
448For example:
449\begin{code}\begin{verbatim}
450>>> x = 1
451>>> eval('x+1')
4522
453>>>
454\end{verbatim}\end{code}
455\item[{\tt exec(s)}]
456Takes a string as argument and parses and evaluates it as a sequence of
457{\Python} statements.
458The string should end with a newline (\verb"'\n'").
459The statement is executed using the current local and global symbol
460tables.
461Syntax errors are reported as exceptions.
462For example:
463\begin{code}\begin{verbatim}
464>>> x = 1
465>>> exec('x = x+1\n')
466>>> x
4672
468>>>
469\end{verbatim}\end{code}
470\item[{\tt float(x)}]
471Converts a number to floating point.
472The argument may be an integer or floating point number.
473\item[{\tt input(s)}]
474Equivalent to
475{\tt eval(raw\_input(s))}.
476As for
477{\tt raw\_input()},
478the argument is optional.
479\item[{\tt len(s)}]
480Returns the length (the number of items) of an object.
481The argument may be a sequence (string, tuple or list) or a mapping
482(dictionary).
483\item[{\tt max(s)}]
484Returns the largest item of a non-empty sequence (string, tuple or list).
485\item[{\tt min(s)}]
486Returns the smallest item of a non-empty sequence (string, tuple or list).
487\item[{\tt open(name, mode)}]
488%.br
489Returns a file object (described earlier under Built-in Types).
490The string arguments are the same as for stdio's
491{\tt fopen()}:
492{\tt 'r'}
493opens the file for reading,
494{\tt 'w'}
495opens it for writing (truncating an existing file),
496{\tt 'a'}
497opens it for appending.%
498\footnote{
499This function should go into a built-in module
500{\tt io}.
501}
502\item[{\tt range()}]
503This is a versatile function to create lists containing arithmetic
504progressions of integers.
505With two integer arguments, it returns the ascending sequence of
506integers starting at the first and ending one before the second
507argument.
508A single argument is used as the end point of the sequence, with 0 used
509as the starting point.
510A third argument specifies the step size; negative steps are allowed and
511work as expected, but don't specify a zero step.
512The resulting list may be empty.
513For example:
514\begin{code}\begin{verbatim}
515>>> range(10)
516[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
517>>> range(1, 1+10)
518[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
519>>> range(0, 30, 5)
520[0, 5, 10, 15, 20, 25]
521>>> range(0, 10, 3)
522[0, 3, 6, 9]
523>>> range(0, -10, -1)
524[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
525>>> range(0)
526[]
527>>> range(1, 0)
528[]
529>>>
530\end{verbatim}\end{code}
531\item[{\tt raw\_input(s)}]
532%.br
533The argument is optional; if present, it is written to standard output
534without a trailing newline.
535The function then reads a line from input, converts it to a string
536(stripping a trailing newline), and returns that.
537EOF is reported as an exception.
538For example:
539\begin{code}\begin{verbatim}
540>>> raw_input('Type anything: ')
541Type anything: Teenage Mutant Ninja Turtles
542'Teenage Mutant Ninja Turtles'
543>>>
544\end{verbatim}\end{code}
545\item[{\tt type(x)}]
546Returns the type of an object.
547Types are objects themselves:
548the type of a type object is its own type.
549\end{description}
550
551\section{Built-in Modules}
552
553The modules described in this section are built into the interpreter.
554They must be imported using
555{\tt import}.
556Some modules are not always available; it is a configuration option to
557provide them.
558Details are listed with the descriptions, but the best way to see if
559a module exists in a particular implementation is to attempt to import
560it.
561
562\subsection{Built-in Module {\tt sys}}
563
564This module provides access to some variables used or maintained by the
565interpreter and to functions that interact strongly with the interpreter.
566It is always available.
567\begin{description}
568\item[{\tt argv}]
569The list of command line arguments passed to a {\Python} script.
570{\tt sys.argv[0]}
571is the script name.
572If no script name was passed to the {\Python} interpreter,
573{\tt sys.argv}
574is empty.
575\item[{\tt exit(n)}]
576Exits from {\Python} with numeric exit status
577{\tt n}.
578This closes all open files and performs other cleanup-actions required by
579the interpreter (but
580{\em finally clauses}
581of
582{\tt try}
583statements are not executed!).
584\item[{\tt modules}]
585Gives the list of modules that have already been loaded.
586This can be manipulated to force reloading of modules and other tricks.
587\item[{\tt path}]
588A list of strings that specifies the search path for modules.
589Initialized from the environment variable {\tt PYTHONPATH}, or an
590installation-dependent default.
591\item[{\tt ps1,~ps2}]
592Strings specifying the primary and secondary prompt of the interpreter.
593These are only defined if the interpreter is in interactive mode.
594Their initial values in this case are
595{\tt '>>> '}
596and
597{\tt '... '}.
598\item[{\tt stdin, stdout, stderr}]
599%.br
600File objects corresponding to the interpreter's standard input, output
601and error streams.
602{\tt sys.stdin}
603is used for all interpreter input except for scripts but including calls
604to
605{\tt input()}
606and
607{\tt raw\_input()}.
608{\tt sys.stdout}
609is used for the output of
610{\tt print} and expression statements
611and for the prompts of
612{\tt input()}
613and
614{\tt raw\_input()}.
615The interpreter's own prompts and its error messages are written to
616stderr.
617Assigning to
618{\tt sys.stderr}
619has no effect on the interpreter; it can be used to write error messages
620to stderr using
621{\tt print}.
622\end{description}
623
624\subsection{Built-in Module {\tt math}}
625
626This module is always available.
627It provides access to the mathematical functions defined by the C
628standard.
629They are:
630{\tt acos(x)},
631{\tt asin(x)},
632{\tt atan(x)},
633{\tt atan2(x,y)},
634{\tt ceil(x)},
635{\tt cos(x)},
636{\tt cosh(x)},
637{\tt exp(x)},
638{\tt fabs(x)},
639{\tt floor(x)},
640%{\tt fmod(...)} XXX not yet
641%{\tt frexp(...)} XXX not yet
642%{\tt ldexp(...)} XXX not yet
643{\tt log(x)},
644{\tt log10(x)},
645%{\tt modf(...)} XXX not yet
646{\tt pow(x,y)},
647{\tt sin(x)},
648{\tt sinh(x)},
649{\tt sqrt(x)},
650{\tt tan(x)},
651{\tt tanh(x)}.
652
653It also defines two mathematical constants:
654{\tt pi}
655and
656{\tt e}.
657
658\subsection{Built-in Module {\tt time}}
659
660This module provides various time-related functions.
661It is always available.
662Functions are:
663\begin{description}
664\item[{\tt sleep(secs)}]
665Suspends execution for the given number of seconds.
666\item[{\tt time()}]
667Returns the time in seconds since the Epoch (Thursday January 1,
66800:00:00, 1970 UCT on \UNIX\ machines).
669\end{description}
670
671\noindent
672In some versions (Amoeba, Mac) the following functions also exist:
673\begin{description}
674\item[{\tt millisleep(msecs)}]
675Suspends execution for the given number of milliseconds.
676\item[{\tt millitimer()}]
677Returns the number of milliseconds of real time elapsed since some point
678in the past that is fixed per execution of the python interpreter (but
679may change in each following run).
680\end{description}
681
682\noindent
683The granularity of the milliseconds functions may be more than a
684millisecond (100 msecs on Amoeba, 1/60 sec on the Mac).
685
686\subsection{Built-in Module {\tt posix}}
687
688This module provides access to operating system functionality that is
689standardized by the C Standard and the POSIX standard (a thinly diguised
690{\UNIX} interface).
691It is available in all {\Python} versions except on the Macintosh.
692Errors are reported exceptions.
693It defines the following items:
694\begin{description}
695\item[{\tt chdir(path)}]
696Changes the current directory to
697{\tt path}.
698\item[{\tt chmod(path, mode)}]
699Change the mode of
700{\tt path}
701to the numeric
702{\tt mode}.
703\item[{\tt environ}]
704A dictionary representing the string environment at the time
705the interpreter was started.
706(Modifying this dictionary does not affect the string environment of the
707interpreter.)
708For example,
709{\tt posix.environ['HOME']}
710is the pathname of your home directory, equivalent to
711{\tt getenv("HOME")}
712in C.
713\item[{\tt error = 'posix.error'}]
714%.br
715The exception raised when an POSIX function returns an error.
716The value accompanying this exception is a pair containing the numeric
717error code from
718{\tt errno}
719and the corresponding string, as would be printed by the C function
720{\tt perror()}.
721\item[{\tt getcwd()}]
722Returns a string representing the current working directory.
723\item[{\tt link(src, dst)}]
724Creates a hard link pointing to
725{\tt src}
726named
727{\tt dst}.
728\item[{\tt listdir(path)}]
729Returns a list containing the names of the entries in the
730directory.
731The list is in arbitrary order.
732It includes the special entries
733{\tt '.'}
734and
735{\tt '..'}
736if they are present in the directory.
737\item[{\tt mkdir(path, mode)}]
738Creates a directory named
739{\tt path}
740with numeric mode
741{\tt mode}.
742\item[{\tt rename(src, dst)}]
743Renames the file or directory
744{\tt src}
745to
746{\tt dst}.
747\item[{\tt rmdir(path)}]
748Removes the directory
749{\tt path}.
750\item[{\tt stat(path)}]
751Performs a
752{\em stat}
753system call on the given path.
754The return value is a tuple of at least 10 integers giving the most
755important (and portable) members of the
756{\em stat}
757structure, in the order
758{\tt st\_mode},
759{\tt st\_ino},
760{\tt st\_dev},
761{\tt st\_nlink},
762{\tt st\_uid},
763{\tt st\_gid},
764{\tt st\_size},
765{\tt st\_atime},
766{\tt st\_mtime},
767{\tt st\_ctime}.
768More items may be added at the end by some implementations.
769\item[{\tt system(command)}]
770Executes the command (a string) in a subshell.
771This is implemented by calling the Standard C function
772{\tt system()},
773and has the same limitations.
774Changes to
775{\tt posix.environ},
776{\tt sys.stdin}
777etc. are not reflected in the environment of the executed command.
778The return value is the exit status of the process as returned by
779Standard C
780{\tt system()}.
781\item[{\tt umask(mask)}]
782Sets the current numeric umask and returns the previous umask.
783\item[{\tt unlink(path)}]
784Unlinks the file
785{\tt path}.
786\item[{\tt utimes(path, (atime, mtime))}]
787%.br
788Sets the access and modified time of the file to the given values.
789(The second argument is a tuple of two items.)
790\end{description}
791
792The following functions are only available on systems that support
793symbolic links:
794\begin{description}
795\item[{\tt lstat(path)}]
796Like
797{\tt stat()},
798but does not follow symbolic links.
799\item[{\tt readlink(path)}]
800Returns a string representing the path to which the symbolic link
801points.
802\item[{\tt symlink(src, dst)}]
803Creates a symbolic link pointing to
804{\tt src}
805named
806{\tt dst}.
807\end{description}
808
809\subsection{Built-in Module {\tt stdwin}}
810
811This module defines several new object types and functions that
812provide access to the functionality of the Standard Window System
813Interface, STDWIN [CWI report CR-R8817].
814It is available on systems to which STDWIN has been ported (which is
815most systems).
816It is only available if the {\tt DISPLAY} environment variable is set
817or an explicit `{\tt -display \it displayname}' argument is passed to
818the interpreter.
819
820Functions have names that usually resemble their C STDWIN counterparts
821with the initial `w' dropped.
822Points are represented by pairs of integers; rectangles
823by pairs of points.
824For a complete description of STDWIN please refer to the documentation
825of STDWIN for C programmers (aforementioned CWI report).
826\subsubsection{Functions Defined in Module {\tt stdwin}}
827
828The following functions are defined in the {\tt stdwin} module:
829\begin{description}
830\item[{\tt open(title)}]
831%.br
832Opens a new window whose initial title is given by the string argument.
833Returns a window object; window object methods are described below.%
834\footnote{
835The {\Python} version of STDWIN does not support draw procedures; all
836drawing requests are reported as draw events.
837}
838\item[{\tt getevent()}]
839%.br
840Waits for and returns the next event.
841An event is returned as a triple: the first element is the event
842type, a small integer; the second element is the window object to which
843the event applies, or
844{\tt None}
845if it applies to no window in particular;
846the third element is type-dependent.
847Names for event types and command codes are defined in the standard
848module
849{\tt stdwinevent}.
850\item[{\tt setdefwinpos(h, v)}]
851%.br
852Sets the default window position.
853\item[{\tt setdefwinsize(width, height)}]
854%.br
855Sets the default window size.
856\item[{\tt menucreate(title)}]
857%.br
858Creates a menu object referring to a global menu (a menu that appears in
859all windows).
860Methods of menu objects are described below.
861\item[{\tt fleep()}]
862%.br
863Causes a beep or bell (or perhaps a `visual bell' or flash, hence the
864name).
865\item[{\tt message(string)}]
866%.br
867Displays a dialog box containing the string.
868The user must click OK before the function returns.
869\item[{\tt askync(prompt, default)}]
870%.br
871Displays a dialog that prompts the user to answer a question with yes or
872no.
873The function returns 0 for no, 1 for yes.
874If the user hits the Return key, the default (which must be 0 or 1) is
875returned.
876If the user cancels the dialog, the
877{\tt KeyboardInterrupt}
878exception is raised.
879\item[{\tt askstr(prompt, default)}]
880%.br
881Displays a dialog that prompts the user for a string.
882If the user hits the Return key, the default string is returned.
883If the user cancels the dialog, the
884{\tt KeyboardInterrupt}
885exception is raised.
886\item[{\tt askfile(prompt, default, new)}]
887%.br
888Asks the user to specify a filename.
889If
890{\tt new}
891is zero it must be an existing file; otherwise, it must be a new file.
892If the user cancels the dialog, the
893{\tt KeyboardInterrupt}
894exception is raised.
895\item[{\tt setcutbuffer(i, string)}]
896%.br
897Stores the string in the system's cut buffer number
898{\tt i},
899where it can be found (for pasting) by other applications.
900On X11, there are 8 cut buffers (numbered 0..7).
901Cut buffer number 0 is the `clipboard' on the Macintosh.
902\item[{\tt getcutbuffer(i)}]
903%.br
904Returns the contents of the system's cut buffer number
905{\tt i}.
906\item[{\tt rotatebutbuffers(n)}]
907%.br
908On X11, this rotates the 8 cut buffers by
909{\tt n}.
910Ignored on the Macintosh.
911\item[{\tt getselection(i)}]
912%.br
913Returns X11 selection number
914{\tt i.}
915Selections are not cut buffers.
916Selection numbers are defined in module
917{\tt stdwinevents}.
918Selection {\tt WS\_PRIMARY} is the
919{\em primary}
920selection (used by
921xterm,
922for instance);
923selection {\tt WS\_SECONDARY} is the
924{\em secondary}
925selection; selection {\tt WS\_CLIPBOARD} is the
926{\em clipboard}
927selection (used by
928xclipboard).
929On the Macintosh, this always returns an empty string.
930\item[{\tt resetselection(i)}]
931%.br
932Resets selection number
933{\tt i},
934if this process owns it.
935(See window method
936{\tt setselection()}).
937\item[{\tt baseline()}]
938%.br
939Return the baseline of the current font (defined by STDWIN as the
940vertical distance between the baseline and the top of the
941characters).%
942\footnote{
943There is no way yet to set the current font.
944This will change in a future version.
945}
946\item[{\tt lineheight()}]
947%.br
948Return the total line height of the current font.
949\item[{\tt textbreak(str, width)}]
950%.br
951Return the number of characters of the string that fit into a space of
952{\tt width}
953bits wide when drawn in the curent font.
954\item[{\tt textwidth(str)}]
955%.br
956Return the width in bits of the string when drawn in the current font.
957\subsubsection{Window Object Methods}
958\end{description}
959
960Window objects are created by
961{\tt stdwin.open()}.
962There is no explicit function to close a window; windows are closed when
963they are garbage-collected.
964Window objects have the following methods:
965\begin{description}
966\item[{\tt begindrawing()}]
967Returns a drawing object, whose methods (described below) allow drawing
968in the window.
969\item[{\tt change(rect)}]
970Invalidates the given rectangle; this may cause a draw event.
971\item[{\tt gettitle()}]
972Returns the window's title string.
973\item[{\tt getdocsize()}]
974Returns a pair of integers giving the size of the document as set by
975{\tt setdocsize()}.
976\item[{\tt getorigin()}]
977Returns a pair of integers giving the origin of the window with respect
978to the document.
979\item[{\tt getwinsize()}]
980Returns a pair of integers giving the size of the window.
981\item[{\tt menucreate(title)}]
982Creates a menu object referring to a local menu (a menu that appears
983only in this window).
984Methods menu objects are described below.
985\item[{\tt scroll(rect,~point)}]
986Scrolls the given rectangle by the vector given by the point.
987\item[{\tt setwincursor(name)}]
988Sets the window cursor to a cursor of the given name.
989It raises the
990{\tt Runtime\-Error}
991exception if no cursor of the given name exists.
992Suitable names are
993{\tt 'ibeam'},
994{\tt 'arrow'},
995{\tt 'cross'},
996{\tt 'watch'}
997and
998{\tt 'plus'}.
999On X11, there are many more (see
1000{\tt <X11/cursorfont.h>}).
1001\item[{\tt setdocsize(point)}]
1002Sets the size of the drawing document.
1003\item[{\tt setorigin(point)}]
1004Moves the origin of the window to the given point in the document.
1005\item[{\tt setselection(i, str)}]
1006Attempts to set X11 selection number
1007{\tt i}
1008to the string
1009{\tt str}.
1010(See stdwin method
1011{\tt getselection()}
1012for the meaning of
1013{\tt i}.)
1014Returns true if it succeeds.
1015If it succeeds, the window ``owns'' the selection until
1016(a) another applications takes ownership of the selection; or
1017(b) the window is deleted; or
1018(c) the application clears ownership by calling
1019{\tt stdwin.resetselection(i)}.
1020When another application takes ownership of the selection, a
1021{\tt WE\_LOST\_SEL}
1022event is received for no particular window and with the selection number
1023as detail.
1024Ignored on the Macintosh.
1025\item[{\tt settitle(title)}]
1026Sets the window's title string.
1027\item[{\tt settimer(dsecs)}]
1028Schedules a timer event for the window in
1029{\tt dsecs/10}
1030seconds.
1031\item[{\tt show(rect)}]
1032Tries to ensure that the given rectangle of the document is visible in
1033the window.
1034\item[{\tt textcreate(rect)}]
1035Creates a text-edit object in the document at the given rectangle.
1036Methods of text-edit objects are described below.
1037\end{description}
1038
1039\subsubsection{Drawing Object Methods}
1040
1041Drawing objects are created exclusively by the window method
1042{\tt begindrawing()}.
1043Only one drawing object can exist at any given time; the drawing object
1044must be deleted to finish drawing.
1045No drawing object may exist when
1046{\tt stdwin.getevent()}
1047is called.
1048Drawing objects have the following methods:
1049\begin{description}
1050\item[{\tt box(rect)}]
1051Draws a box around a rectangle.
1052\item[{\tt circle(center, radius)}]
1053%.br
1054Draws a circle with given center point and radius.
1055\item[{\tt elarc(center, (rh, rv), (a1, a2))}]
1056%.br
1057Draws an elliptical arc with given center point.
1058{\tt (rh, rv)}
1059gives the half sizes of the horizontal and vertical radii.
1060{\tt (a1, a2)}
1061gives the angles (in degrees) of the begin and end points.
10620 degrees is at 3 o'clock, 90 degrees is at 12 o'clock.
1063\item[{\tt erase(rect)}]
1064Erases a rectangle.
1065\item[{\tt invert(rect)}]
1066Inverts a rectangle.
1067\item[{\tt line(p1, p2)}]
1068Draws a line from point
1069{\tt p1}
1070to
1071{\tt p2}.
1072\item[{\tt paint(rect)}]
1073Fills a rectangle.
1074\item[{\tt text(p, str)}]
1075Draws a string starting at point p (the point specifies the
1076top left coordinate of the string).
1077\item[{\tt shade(rect, percent)}]
1078%.br
1079Fills a rectangle with a shading pattern that is about
1080{\tt percent}
1081percent filled.
1082\item[{\tt xorline(p1, p2)}]
1083Draws a line in XOR mode.
1084\item[{\tt baseline(), lineheight(), textbreak(), textwidth()}]
1085%.br
1086These functions are similar to the corresponding functions described
1087above for the
1088{\tt stdwin}
1089module, but use the current font of the window instead of the (global)
1090default font.
1091\end{description}
1092
1093\subsubsection{Menu Object Methods}
1094
1095A menu object represents a menu.
1096The menu is destroyed when the menu object is deleted.
1097The following methods are defined:
1098\begin{description}
1099\item[{\tt additem(text, shortcut)}]
1100%.br
1101Adds a menu item with given text.
1102The shortcut must be a string of length 1, or omitted (to specify no
1103shortcut).
1104\item[{\tt setitem(i, text)}]
1105Sets the text of item number
1106{\tt i}.
1107\item[{\tt enable(i, flag)}]
1108Enables or disables item
1109{\tt i}.
1110\item[{\tt check(i, flag)}]
1111Sets or clears the
1112{\em check mark}
1113for item
1114{\tt i}.
1115\end{description}
1116
1117\subsubsection{Text-edit Object Methods}
1118
1119A text-edit object represents a text-edit block.
1120For semantics, see the STDWIN documentation for C programmers.
1121The following methods exist:
1122\begin{description}
1123\item[{\tt arrow(code)}]
1124Passes an arrow event to the text-edit block.
1125The
1126{\tt code}
1127must be one of
1128{\tt WC\_LEFT},
1129{\tt WC\_RIGHT},
1130{\tt WC\_UP}
1131or
1132{\tt WC\_DOWN}
1133(see module
1134{\tt stdwinevents}).
1135\item[{\tt draw(rect)}]
1136Passes a draw event to the text-edit block.
1137The rectangle specifies the redraw area.
1138\item[{\tt event(type, window, detail)}]
1139%.br
1140Passes an event gotten from
1141{\tt stdwin.getevent()}
1142to the text-edit block.
1143Returns true if the event was handled.
1144\item[{\tt getfocus()}]
1145Returns 2 integers representing the start and end positions of the
1146focus, usable as slice indices on the string returned by
1147{\tt getfocustext()}.
1148\item[{\tt getfocustext()}]
1149Returns the text in the focus.
1150\item[{\tt getrect()}]
1151Returns a rectangle giving the actual position of the text-edit block.
1152(The bottom coordinate may differ from the initial position because
1153the block automatically shrinks or grows to fit.)
1154\item[{\tt gettext()}]
1155Returns the entire text buffer.
1156\item[{\tt move(rect)}]
1157Specifies a new position for the text-edit block in the document.
1158\item[{\tt replace(str)}]
1159Replaces the focus by the given string.
1160The new focus is an insert point at the end of the string.
1161\item[{\tt setfocus(i,~j)}]
1162Specifies the new focus.
1163Out-of-bounds values are silently clipped.
1164\end{description}
1165
1166\subsection{Built-in Module {\tt amoeba}}
1167
1168This module provides some object types and operations useful for
1169Amoeba applications.
1170It is only available on systems that support Amoeba operations.
1171RPC errors and other Amoeba errors are reported as the exception
1172{\tt amoeba.error = 'amoeba.error'}.
1173The module
1174{\tt amoeba}
1175defines the following items:
1176\begin{description}
1177\item[{\tt name\_append(path,~cap)}]
1178%.br
1179Stores a capability in the Amoeba directory tree.
1180Arguments are the pathname (a string) and the capability (a capability
1181object as returned by
1182{\tt name\_lookup()}).
1183\item[{\tt name\_delete(path)}]
1184%.br
1185Deletes a capability from the Amoeba directory tree.
1186Argument is the pathname.
1187\item[{\tt name\_lookup(path)}]
1188%.br
1189Looks up a capability.
1190Argument is the pathname.
1191Returns a
1192{\em capability}
1193object, to which various interesting operations apply, described below.
1194\item[{\tt name\_replace(path,~cap)}]
1195%.br
1196Replaces a capability in the Amoeba directory tree.
1197Arguments are the pathname and the new capability.
1198(This differs from
1199{\tt name\_append()}
1200in the behavior when the pathname already exists:
1201{\tt name\_append()}
1202finds this an error while
1203{\tt name\_replace()}
1204allows it, as its name suggests.)
1205\item[{\tt capv}]
1206A table representing the capability environment at the time the
1207interpreter was started.
1208(Alas, modifying this table does not affect the capability environment
1209of the interpreter.)
1210For example,
1211{\tt amoeba.capv['ROOT']}
1212is the capability of your root directory, similar to
1213{\tt getcap("ROOT")}
1214in C.
1215\item[{\tt error = 'amoeba.error'}]
1216%.br
1217The exception raised when an Amoeba function returns an error.
1218The value accompanying this exception is a pair containing the numeric
1219error code and the corresponding string, as returned by the C function
1220{\tt err\_why()}.
1221\item[{\tt timeout(msecs)}]
1222%.br
1223Sets the transaction timeout, in milliseconds.
1224Returns the previous timeout.
1225Initially, the timeout is set to 2 seconds by the {\Python} interpreter.
1226\end{description}
1227
1228\subsubsection{Capability Operations}
1229
1230Capabilities are written in a convenient ASCII format, also used by the
1231Amoeba utilities
1232{\em c2a}(U)
1233and
1234{\em a2c}(U).
1235For example:
1236\begin{code}\begin{verbatim}
1237>>> amoeba.name_lookup('/profile/cap')
1238aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a
1239>>>
1240\end{verbatim}\end{code}
1241The following methods are defined for capability objects.
1242\begin{description}
1243\item[{\tt dir\_list()}]
1244Returns a list of the names of the entries in an Amoeba directory.
1245\item[{\tt b\_read(offset, maxsize)}]
1246%.br
1247Reads (at most)
1248{\tt maxsize}
1249bytes from a bullet file at offset
1250{\tt offset.}
1251The data is returned as a string.
1252EOF is reported as an empty string.
1253\item[{\tt b\_size()}]
1254Returns the size of a bullet file.
1255\item[{\tt dir\_append(), dir\_delete(), dir\_lookup(), dir\_replace()}]
1256%.br
1257Like the corresponding
1258{\tt name\_*}
1259functions, but with a path relative to the capability.
1260(For paths beginning with a slash the capability is ignored, since this
1261is the defined semantics for Amoeba.)
1262\item[{\tt std\_info()}]
1263Returns the standard info string of the object.
1264\item[{\tt tod\_gettime()}]
1265Returns the time (in seconds since the Epoch, in UCT, as for POSIX) from
1266a time server.
1267\item[{\tt tod\_settime(t)}]
1268Sets the time kept by a time server.
1269\end{description}
1270
1271\subsection{Built-in Module {\tt audio}}
1272
1273This module provides rudimentary access to the audio I/O device
1274{\tt /dev/audio}
1275on the Silicon Graphics Personal IRIS; see audio(7).
1276It supports the following operations:
1277\begin{description}
1278\item[{\tt setoutgain(n)}]
1279Sets the output gain (0-255).
1280\item[{\tt getoutgain()}]
1281Returns the output gain.
1282\item[{\tt setrate(n)}]
1283Sets the sampling rate: 1=32K/sec, 2=16K/sec, 3=8K/sec.
1284\item[{\tt setduration(n)}]
1285Sets the `sound duration' in units of 1/100 seconds.
1286\item[{\tt read(n)}]
1287Reads a chunk of
1288{\tt n}
1289sampled bytes from the audio input (line in or microphone).
1290The chunk is returned as a string of length n.
1291Each byte encodes one sample as a signed 8-bit quantity using linear
1292encoding.
1293This string can be converted to numbers using {\tt chr2num()} described
1294below.
1295\item[{\tt write(buf)}]
1296Writes a chunk of samples to the audio output (speaker).
1297\end{description}
1298
1299These operations support asynchronous audio I/O:
1300\begin{description}
1301\item[{\tt start\_recording(n)}]
1302%.br
1303Starts a second thread (a process with shared memory) that begins reading
1304{\tt n}
1305bytes from the audio device.
1306The main thread immediately continues.
1307\item[{\tt wait\_recording()}]
1308%.br
1309Waits for the second thread to finish and returns the data read.
1310\item[{\tt stop\_recording()}]
1311%.br
1312Makes the second thread stop reading as soon as possible.
1313Returns the data read so far.
1314\item[{\tt poll\_recording()}]
1315%.br
1316Returns true if the second thread has finished reading (so
1317{\tt wait\_recording()} would return the data without delay).
1318\item[{\tt start\_playing(chunk)}, {\tt wait\_playing()},
1319{\tt stop\_playing()}, {\tt poll\_playing()}]
1320%.br
1321Similar but for output.
1322{\tt stop\_playing()}
1323returns a lower bound for the number of bytes actually played (not very
1324accurate).
1325\end{description}
1326
1327The following operations do not affect the audio device but are
1328implemented in C for efficiency:
1329\begin{description}
1330\item[{\tt amplify(buf, f1, f2)}]
1331%.br
1332Amplifies a chunk of samples by a variable factor changing from
1333{\tt f1}/256 to {\tt f2}/256.
1334Negative factors are allowed.
1335Resulting values that are to large to fit in a byte are clipped.
1336\item[{\tt reverse(buf)}]
1337%.br
1338Returns a chunk of samples backwards.
1339\item[{\tt add(buf1, buf2)}]
1340%.br
1341Bytewise adds two chunks of samples.
1342Bytes that exceed the range are clipped.
1343If one buffer shorter, it is assumed to be padded with zeros.
1344\item[{\tt chr2num(buf)}]
1345%.br
1346Converts a string of sampled bytes as returned by {\tt read()} into
1347a list containing the numeric values of the samples.
1348\item[{\tt num2chr(list)}]
1349%.br
1350Converts a list as returned by
1351{\tt chr2num()}
1352back to a buffer acceptable by
1353{\tt write()}.
1354\end{description}
1355
1356\subsection{Built-in Module {\tt gl}}
1357
1358This module provides access to the Silicon Graphics
1359{\em Graphics Library}.
1360It is available only on Silicon Graphics machines.
1361
1362{\bf Warning:}
1363Some illegal calls to the GL library cause the {\Python} interpreter to dump
1364core.
1365In particular, the use of most GL calls is unsafe before the first
1366window is opened.
1367
1368The module is too large to document here in its entirety, but the
1369following should help you to get started.
1370The parameter conventions for the C functions are translated to {\Python} as
1371follows:
1372
1373\begin{itemize}
1374\item
1375All (short, long, unsigned) int values are represented by {\Python}
1376integers.
1377\item
1378All float and double values are represented by {\Python} floating point
1379numbers.
1380In most cases, {\Python} integers are also allowed.
1381\item
1382All arrays are represented by one-dimensional {\Python} lists.
1383In most cases, tuples are also allowed.
1384\item
1385All string and character arguments are represented by {\Python} strings,
1386e.g.,
1387{\tt winopen('Hi~There!')}
1388and
1389{\tt rotate(900,~'z')}.
1390\item
1391All (short, long, unsigned) integer arguments or return values that are
1392only used to specify the length of an array argument are omitted.
1393For example, the C call
1394\begin{code}\begin{verbatim}
1395lmdef(deftype, index, np, props)
1396\end{verbatim}\end{code}
1397is translated to {\Python} as
1398\begin{code}\begin{verbatim}
1399lmdef(deftype, index, props)
1400\end{verbatim}\end{code}
1401\item
1402Output arguments are omitted from the argument list; they are
1403transmitted as function return values instead.
1404If more than one value must be returned, the return value is a tuple.
1405If the C function has both a regular return value (that is not omitted
1406because of the previous rule) and an output argument, the return value
1407comes first in the tuple.
1408Examples: the C call
1409\begin{code}\begin{verbatim}
1410getmcolor(i, &red, &green, &blue)
1411\end{verbatim}\end{code}
1412is translated to {\Python} as
1413\begin{code}\begin{verbatim}
1414red, green, blue = getmcolor(i)
1415\end{verbatim}\end{code}
1416\end{itemize}
1417
1418The following functions are non-standard or have special argument
1419conventions:
1420\begin{description}
1421\item[{\tt varray()}]
1422Equivalent to but faster than a number of
1423{\tt v3d()}
1424calls.
1425The argument is a list (or tuple) of points.
1426Each point must be a tuple of coordinates (x, y, z) or (x, y).
1427The points may be 2- or 3-dimensional but must all have the
1428same dimension.
1429Float and int values may be mixed however.
1430The points are always converted to 3D double precision points
1431by assuming z=0.0 if necessary (as indicated in the man page),
1432and for each point
1433{\tt v3d()}
1434is called.
1435\item[{\tt nvarray()}]
1436Equivalent to but faster than a number of
1437{\tt n3f}
1438and
1439{\tt v3f}
1440calls.
1441The argument is an array (list or tuple) of pairs of normals and points.
1442Each pair is a tuple of a point and a normal for that point.
1443Each point or normal must be a tuple of coordinates (x, y, z).
1444Three coordinates must be given.
1445Float and int values may be mixed.
1446For each pair,
1447{\tt n3f()}
1448is called for the normal, and then
1449{\tt v3f()}
1450is called for the point.
1451\item[{\tt vnarray()}]
1452Similar to
1453{\tt nvarray()}
1454but the pairs have the point first and the normal second.
1455\item[{\tt nurbssurface(s\_k[], t\_k[], ctl[][], s\_ord, t\_ord, type)}]
1456%.br
1457Defines a nurbs surface.
1458The dimensions of
1459{\tt ctl[][]}
1460are computed as follows:
1461{\tt [len(s\_k)~-~s\_ord]},
1462{\tt [len(t\_k)~-~t\_ord]}.
1463\item[{\tt nurbscurve(knots, ctlpoints, order, type)}]
1464%.br
1465Defines a nurbs curve.
1466The length of ctlpoints is
1467{\tt len(knots)~-~order}.
1468\item[{\tt pwlcurve(points, type)}]
1469%.br
1470Defines a piecewise-linear curve.
1471{\tt points}
1472is a list of points.
1473{\tt type}
1474must be
1475{\tt N\_ST}.
1476\item[{\tt pick(n), select(n)}]
1477%.br
1478The only argument to these functions specifies the desired size of the
1479pick or select buffer.
1480\item[{\tt endpick(), endselect()}]
1481%.br
1482These functions have no arguments.
1483They return a list of integers representing the used part of the
1484pick/select buffer.
1485No method is provided to detect buffer overrun.
1486\end{description}
1487
1488Here is a tiny but complete example GL program in {\Python}:
1489\begin{code}\begin{verbatim}
1490import gl, GL, time
1491
1492def main():
1493 gl.foreground()
1494 gl.prefposition(500, 900, 500, 900)
1495 w = gl.winopen('CrissCross')
1496 gl.ortho2(0.0, 400.0, 0.0, 400.0)
1497 gl.color(GL.WHITE)
1498 gl.clear()
1499 gl.color(GL.RED)
1500 gl.bgnline()
1501 gl.v2f(0.0, 0.0)
1502 gl.v2f(400.0, 400.0)
1503 gl.endline()
1504 gl.bgnline()
1505 gl.v2f(400.0, 0.0)
1506 gl.v2f(0.0, 400.0)
1507 gl.endline()
1508 time.sleep(5)
1509
1510main()
1511\end{verbatim}\end{code}
1512
1513\subsection{Built-in Module {\tt pnl}}
1514
1515This module provides access to the
1516{\em Panel Library}
1517built by NASA Ames (write to
1518{\tt panel-request@nas.nasa.gov}
1519to get it).
1520All access to it should be done through the standard module
1521{\tt panel},
1522which transparantly exports most functions from
1523{\tt pnl}
1524but redefines
1525{\tt pnl.dopanel()}.
1526
1527{\bf Warning:}
1528the {\Python} interpreter will dump core if you don't create a GL window
1529before calling
1530{\tt pnl.mkpanel()}.
1531
1532The module is too large to document here in its entirety.
1533
1534\section{Standard Modules}
1535
1536The following standard modules are defined.
1537They are available in one of the directories in the default module
1538search path (try printing
1539{\tt sys.path}
1540to find out the default search path.)
1541
1542\subsection{Standard Module {\tt string}}
1543
1544This module defines some constants useful for checking character
1545classes, some exceptions, and some useful string functions.
1546The constants are:
1547\begin{description}
1548\item[{\tt digits}]
1549The string
1550{\tt '0123456789'}.
1551\item[{\tt hexdigits}]
1552The string
1553{\tt '0123456789abcdefABCDEF'}.
1554\item[{\tt letters}]
1555The concatenation of the strings
1556{\tt lowercase}
1557and
1558{\tt uppercase}
1559described below.
1560\item[{\tt lowercase}]
1561The string
1562{\tt 'abcdefghijklmnopqrstuvwxyz'}.
1563\item[{\tt octdigits}]
1564The string
1565{\tt '01234567'}.
1566\item[{\tt uppercase}]
1567The string
1568{\tt 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}.
1569\item[{\tt whitespace}]
1570A string containing all characters that are considered whitespace,
1571i.e.,
1572space, tab and newline.
1573This definition is used by
1574{\tt split()}
1575and
1576{\tt strip()}.
1577\end{description}
1578
1579The exceptions are:
1580\begin{description}
1581\item[{\tt atoi\_error = 'non-numeric argument to string.atoi'}]
1582%.br
1583Exception raised by
1584{\tt atoi}
1585when a non-numeric string argument is detected.
1586The exception argument is the offending string.
1587\item[{\tt index\_error = 'substring not found in string.index'}]
1588%.br
1589Exception raised by
1590{\tt index}
1591when
1592{\tt sub}
1593is not found.
1594The argument are the offending arguments to index: {\tt (s, sub)}.
1595\end{description}
1596
1597The functions are:
1598\begin{description}
1599\item[{\tt atoi(s)}]
1600Converts a string to a number.
1601The string must consist of one or more digits, optionally preceded by a
1602sign ({\tt '+'} or {\tt '-'}).
1603\item[{\tt index(s, sub)}]
1604Returns the lowest index in
1605{\tt s}
1606where the substring
1607{\tt sub}
1608is found.
1609\item[{\tt lower(s)}]
1610Convert letters to lower case.
1611\item[{\tt split(s)}]
1612Returns a list of the whitespace-delimited words of the string
1613{\tt s}.
1614\item[{\tt splitfields(s, sep)}]
1615%.br
1616Returns a list containing the fields of the string
1617{\tt s},
1618using the string
1619{\tt sep}
1620as a separator.
1621The list will have one more items than the number of non-overlapping
1622occurrences of the separator in the string.
1623Thus,
1624{\tt string.splitfields(s, ' ')}
1625is not the same as
1626{\tt string.split(s)},
1627as the latter only returns non-empty words.
1628\item[{\tt strip(s)}]
1629Removes leading and trailing whitespace from the string
1630{\tt s}.
1631\item[{\tt swapcase(s)}]
1632Converts lower case letters to upper case and vice versa.
1633\item[{\tt upper(s)}]
1634Convert letters to upper case.
1635\item[{\tt ljust(s, width), rjust(s, width), center(s, width)}]
1636%.br
1637These functions respectively left-justify, right-justify and center a
1638string in a field of given width.
1639They return a string that is at least
1640{\tt width}
1641characters wide, created by padding the string
1642{\tt s}
1643with spaces until the given width on the right, left or both sides.
1644The string is never truncated.
1645\end{description}
1646
1647\subsection{Standard Module {\tt path}}
1648
1649This module implements some useful functions on POSIX pathnames.
1650\begin{description}
1651\item[{\tt basename(p)}]
1652Returns the base name of pathname
1653{\tt p}.
1654This is the second half of the pair returned by
1655{\tt path.split(p)}.
1656\item[{\tt cat(p, q)}]
1657Performs intelligent pathname concatenation on paths
1658{\tt p}
1659and
1660{\tt q}:
1661If
1662{\tt q}
1663is an absolute path, the return value is
1664{\tt q}.
1665Otherwise, the concatenation of
1666{\tt p}
1667and
1668{\tt q}
1669is returned, with a slash ({\tt '/'}) inserted unless
1670{\tt p}
1671is empty or ends in a slash.
1672\item[{\tt commonprefix(list)}]
1673%.br
1674Returns the longest string that is a prefix of all strings in
1675{\tt list}.
1676If
1677{\tt list}
1678is empty, the empty string ({\tt ''}) is returned.
1679\item[{\tt exists(p)}]
1680Returns true if
1681{\tt p}
1682refers to an existing path.
1683\item[{\tt isdir(p)}]
1684Returns true if
1685{\tt p}
1686refers to an existing directory.
1687\item[{\tt islink(p)}]
1688Returns true if
1689{\tt p}
1690refers to a directory entry that is a symbolic link.
1691Always false if symbolic links are not supported.
1692\item[{\tt ismount(p)}]
1693Returns true if
1694{\tt p}
1695is an absolute path that occurs in the mount table as output by the
1696{\tt /etc/mount}
1697utility.
1698This output is read once when the function is used for the first
1699time.%
1700\footnote{
1701Is there a better way to check for mount points?
1702}
1703\item[{\tt split(p)}]
1704Returns a pair
1705{\tt (head,~tail)}
1706such that
1707{\tt tail}
1708contains no slashes and
1709{\tt path.cat(head, tail)}
1710is equal to
1711{\tt p}.
1712\item[{\tt walk(p, visit, arg)}]
1713%.br
1714Calls the function
1715{\tt visit}
1716with arguments
1717{\tt (arg, dirname, names)}
1718for each directory in the directory tree rooted at
1719{\tt p}
1720(including
1721{\tt p}
1722itself, if it is a directory).
1723The argument
1724{\tt dirname}
1725specifies the visited directory, the argument
1726{\tt names}
1727lists the files in the directory (gotten from
1728{\tt posix.listdir(dirname)}).
1729The
1730{\tt visit}
1731function may modify
1732{\tt names}
1733to influence the set of directories visited below
1734{\tt dirname},
1735e.g.,
1736to avoid visiting certain parts of the tree.
1737(The object referred to by
1738{\tt names}
1739must be modified in place, using
1740{\tt del}
1741or slice assignment.)
1742\end{description}
1743
1744\subsection{Standard Module {\tt getopt}}
1745
1746This module helps scripts to parse the command line arguments in
1747{\tt sys.argv}.
1748It uses the same conventions as the {\UNIX}
1749{\tt getopt()}
1750function.
1751It defines the function
1752{\tt getopt.getopt(args, options)}
1753and the exception
1754{\tt getopt.error}.
1755
1756The first argument to
1757{\tt getopt()}
1758is the argument list passed to the script with its first element
1759chopped off (i.e.,
1760{\tt sys.argv[1:]}).
1761The second argument is the string of option letters that the
1762script wants to recognize, with options that require an argument
1763followed by a colon (i.e., the same format that {\UNIX}
1764{\tt getopt()}
1765uses).
1766The return value consists of two elements: the first is a list of
1767option-and-value pairs; the second is the list of program arguments
1768left after the option list was stripped (this is a trailing slice of the
1769first argument).
1770Each option-and-value pair returned has the option as its first element,
1771prefixed with a hyphen (e.g.,
1772{\tt '-x'}),
1773and the option argument as its second element, or an empty string if the
1774option has no argument.
1775The options occur in the list in the same order in which they were
1776found, thus allowing multiple occurrences.
1777Example:
1778\begin{code}\begin{verbatim}
1779>>> import getopt, string
1780>>> args = string.split('-a -b -cfoo -d bar a1 a2')
1781>>> args
1782['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
1783>>> optlist, args = getopt.getopt(args, 'abc:d:')
1784>>> optlist
1785[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
1786>>> args
1787['a1', 'a2']
1788>>>
1789\end{verbatim}\end{code}
1790The exception
1791{\tt getopt.error = 'getopt error'}
1792is raised when an unrecognized option is found in the argument list or
1793when an option requiring an argument is given none.
1794The argument to the exception is a string indicating the cause of the
1795error.
1796
1797\subsection{Standard Module {\tt rand}}
1798
1799This module implements a pseudo-random number generator similar to
1800{\tt rand()}
1801in C.
1802It defines the following functions:
1803\begin{description}
1804\item[{\tt rand()}]
1805Returns an integer random number in the range [0 ... 32768).
1806\item[{\tt choice(s)}]
1807Returns a random element from the sequence (string, tuple or list)
1808{\tt s.}
1809\item[{\tt srand(seed)}]
1810Initializes the random number generator with the given integral seed.
1811When the module is first imported, the random number is initialized with
1812the current time.
1813\end{description}
1814
1815\subsection{Standard Module {\tt whrandom}}
1816
1817This module implements a Wichmann-Hill pseudo-random number generator.
1818It defines the following functions:
1819\begin{description}
1820\item[{\tt random()}]
1821Returns the next random floating point number in the range [0.0 ... 1.0).
1822\item[{\tt seed(x, y, z)}]
1823Initializes the random number generator from the integers
1824{\tt x},
1825{\tt y}
1826and
1827{\tt z}.
1828When the module is first imported, the random number is initialized
1829using values derived from the current time.
1830\end{description}
1831
1832\subsection{Standard Module {\tt stdwinevents}}
1833
1834This module defines constants used by STDWIN for event types
1835({\tt WE\_ACTIVATE} etc.), command codes ({\tt WC\_LEFT} etc.)
1836and selection types ({\tt WS\_PRIMARY} etc.).
1837Read the file for details.
1838Suggested usage is
1839\begin{code}\begin{verbatim}
1840>>> from stdwinevents import *
1841>>>
1842\end{verbatim}\end{code}
1843
1844\subsection{Standard Module {\tt rect}}
1845
1846This module contains useful operations on rectangles.
1847A rectangle is defined as in module
1848{\tt stdwin}:
1849a pair of points, where a point is a pair of integers.
1850For example, the rectangle
1851\begin{code}\begin{verbatim}
1852(10, 20), (90, 80)
1853\end{verbatim}\end{code}
1854is a rectangle whose left, top, right and bottom edges are 10, 20, 90
1855and 80, respectively.
1856Note that the positive vertical axis points down (as in
1857{\tt stdwin}).
1858
1859The module defines the following objects:
1860\begin{description}
1861\item[{\tt error = 'rect.error'}]
1862%.br
1863The exception raised by functions in this module when they detect an
1864error.
1865The exception argument is a string describing the problem in more
1866detail.
1867\item[{\tt empty}]
1868%.br
1869The rectangle returned when some operations return an empty result.
1870This makes it possible to quickly check whether a result is empty:
1871\begin{code}\begin{verbatim}
1872>>> import rect
1873>>> r1 = (10, 20), (90, 80)
1874>>> r2 = (0, 0), (10, 20)
1875>>> r3 = rect.intersect(r1, r2)
1876>>> if r3 is rect.empty: print 'Empty intersection'
1877Empty intersection
1878>>>
1879\end{verbatim}\end{code}
1880\item[{\tt is\_empty(r)}]
1881%.br
1882Returns true if the given rectangle is empty.
1883A rectangle
1884{\em (left,~top), (right,~bottom)}
1885is empty if
1886{\em left~$\geq$~right}
1887or
1888{\em top~$\leq$~bottom}.
1889\item[{\tt intersect(list)}]
1890%.br
1891Returns the intersection of all rectangles in the list argument.
1892It may also be called with a tuple argument or with two or more
1893rectangles as arguments.
1894Raises
1895{\tt rect.error}
1896if the list is empty.
1897Returns
1898{\tt rect.empty}
1899if the intersection of the rectangles is empty.
1900\item[{\tt union(list)}]
1901%.br
1902Returns the smallest rectangle that contains all non-empty rectangles in
1903the list argument.
1904It may also be called with a tuple argument or with two or more
1905rectangles as arguments.
1906Returns
1907{\tt rect.empty}
1908if the list is empty or all its rectangles are empty.
1909\item[{\tt pointinrect(point, rect)}]
1910%.br
1911Returns true if the point is inside the rectangle.
1912By definition, a point
1913{\em (h,~v)}
1914is inside a rectangle
1915{\em (left,~top),}
1916{\em (right,~bottom)}
1917if
1918{\em left~$\leq$~h~$<$~right}
1919and
1920{\em top~$\leq$~v~$<$~bottom}.
1921\item[{\tt inset(rect, (dh, dv))}]
1922%.br
1923Returns a rectangle that lies inside the
1924{\tt rect}
1925argument by
1926{\tt dh}
1927pixels horizontally
1928and
1929{\tt dv}
1930pixels
1931vertically.
1932If
1933{\tt dh}
1934or
1935{\tt dv}
1936is negative, the result lies outside
1937{\tt rect}.
1938\item[{\tt rect2geom(rect)}]
1939%.br
1940Converts a rectangle to geometry representation:
1941{\em (left,~top),}
1942{\em (width,~height)}.
1943\item[{\tt geom2rect(geom)}]
1944%.br
1945Converts a rectangle given in geometry representation back to the
1946standard rectangle representation
1947{\em (left,~top),}
1948{\em (right,~bottom)}.
1949\end{description}
1950
1951\subsection{Standard Modules {\tt GL} and {\tt DEVICE}}
1952
1953These modules define the constants used by the Silicon Graphics
1954{\em Graphics Library}
1955that C programmers find in the header files
1956{\tt <gl/gl.h>}
1957and
1958{\tt <gl/device.h>}.
1959Read the module files for details.
1960
1961\subsection{Standard Module {\tt panel}}
1962
1963This module should be used instead of the built-in module
1964{\tt pnl}
1965to interface with the
1966{\em Panel Library}.
1967
1968The module is too large to document here in its entirety.
1969One interesting function:
1970\begin{description}
1971\item[{\tt defpanellist(filename)}]
1972%.br
1973Parses a panel description file containing S-expressions written by the
1974{\em Panel Editor}
1975that accompanies the Panel Library and creates the described panels.
1976It returns a list of panel objects.
1977\end{description}
1978
1979{\bf Warning:}
1980the {\Python} interpreter will dump core if you don't create a GL window
1981before calling
1982{\tt panel.mkpanel()}
1983or
1984{\tt panel.defpanellist()}.
1985
1986\subsection{Standard Module {\tt parser}}
1987
1988This module defines a self-contained parser for S-expressions as output
1989by the Panel Editor (which is written in Scheme so it can't help writing
1990S-expressions).
1991The relevant function is
1992{\tt parser.parse\_file(file)}
1993which has a file object (not a filename!) as argument and returns a list
1994of parsed S-expressions.
1995Each S-expression is converted into a {\Python} list, with atoms converted
1996to {\Python} strings and sub-expressions (recursively) to {\Python} lists.
1997For more details, read the module file.
1998
1999\subsection{P.M.}
2000
2001\begin{verse}
2002commands
2003
2004cmp?
2005
2006*cache?
2007
2008localtime?
2009
2010calendar?
2011
2012\_\_dict?
2013\end{verse}
2014
2015\end{document}