11 Internet and WWW Services

node140.html
lib.html
node138.html
node1.html
node270.html
---
# 11 Internet and WWW Services
The modules described in this chapter provide various services to
World-Wide Web (WWW) clients and/or services, and a few modules
related to news and email. They are all implemented in Python. Some
of these modules require the presence of the system-dependent module
sockets, which is currently only fully
supported on Unix and Windows NT. Here is an overview:
---
- 11.1 Standard Module cgi (node140.html#SECTION0012100000000000000000)
- Introduction (node141.html#SECTION0012110000000000000000)
Using the cgi module (node142.html#SECTION0012120000000000000000)
Old classes (node143.html#SECTION0012130000000000000000)
Functions (node144.html#SECTION0012140000000000000000)
Caring about security (node145.html#SECTION0012150000000000000000)
Installing your CGI script on a Unix system (node146.html#SECTION0012160000000000000000)
Testing your CGI script (node147.html#SECTION0012170000000000000000)
Debugging CGI scripts (node148.html#SECTION0012180000000000000000)
Common problems and solutions (node149.html#SECTION0012190000000000000000)
11.2 Standard Module urllib (node150.html#SECTION0012200000000000000000)
11.3 Standard Module httplib (node151.html#SECTION0012300000000000000000)
- HTTP Objects (node152.html#SECTION0012310000000000000000)
Example (node153.html#SECTION0012320000000000000000)
11.4 Standard Module ftplib (node154.html#SECTION0012400000000000000000)
- FTP Objects (node155.html#SECTION0012410000000000000000)
11.5 Standard Module gopherlib (node156.html#SECTION0012500000000000000000)
11.6 Standard Module nntplib (node157.html#SECTION0012600000000000000000)
- NNTP Objects (node158.html#SECTION0012610000000000000000)
11.7 Standard Module urlparse (node159.html#SECTION0012700000000000000000)
11.8 Standard Module sgmllib (node160.html#SECTION0012800000000000000000)
11.9 Standard Module htmllib (node161.html#SECTION0012900000000000000000)
11.10 Standard Module xmllib (node162.html#SECTION00121000000000000000000)
11.11 Standard Module formatter (node163.html#SECTION00121100000000000000000)
- The Formatter Interface (node164.html#SECTION00121110000000000000000)
Formatter Implementations (node165.html#SECTION00121120000000000000000)
The Writer Interface (node166.html#SECTION00121130000000000000000)
Writer Implementations (node167.html#SECTION00121140000000000000000)
11.12 Standard Module rfc822 (node168.html#SECTION00121200000000000000000)
- Message Objects (node169.html#SECTION00121210000000000000000)
11.13 Standard Module mimetools (node170.html#SECTION00121300000000000000000)
- Additional Methods of Message objects (node171.html#SECTION00121310000000000000000)
11.14 Standard Module binhex (node172.html#SECTION00121400000000000000000)
- Notes (node173.html#SECTION00121410000000000000000)
11.15 Standard Module uu (node174.html#SECTION00121500000000000000000)
11.16 Built-in Module binascii (node175.html#SECTION00121600000000000000000)
11.17 Standard Module xdrlib (node176.html#SECTION00121700000000000000000)
- Packer Objects (node177.html#SECTION00121710000000000000000)
Unpacker Objects (node178.html#SECTION00121720000000000000000)
Exceptions (node179.html#SECTION00121730000000000000000)
11.18 Standard Module mailcap (node180.html#SECTION00121800000000000000000)
11.19 Standard Module base64 (node181.html#SECTION00121900000000000000000)
11.20 Standard Module quopri (node182.html#SECTION00122000000000000000000)
11.21 Standard Module SocketServer (node183.html#SECTION00122100000000000000000)
11.22 Standard Module mailbox (node184.html#SECTION00122200000000000000000)
- Mailbox Objects (node185.html#SECTION00122210000000000000000)
11.23 Standard Module mimify (node186.html#SECTION00122300000000000000000)
11.24 Standard Module BaseHTTPServer (node187.html#SECTION00122400000000000000000)
---
node140.html
lib.html
node138.html
node1.html
node270.html
guido@python.org


Other Built-in Types

node15.html
node4.html
node13.html
node1.html
node270.html
---
## Other Built-in Types
The interpreter supports several other kinds of objects.
Most of these support only one or two operations.
---
- Modules (node15.html#SECTION003171000000000000000)
Classes and Class Instances (node16.html#SECTION003172000000000000000)
Functions (node17.html#SECTION003173000000000000000)
Methods (node18.html#SECTION003174000000000000000)
Code Objects (node19.html#SECTION003175000000000000000)
Type Objects (node20.html#SECTION003176000000000000000)
The Null Object (node21.html#SECTION003177000000000000000)
File Objects (node22.html#SECTION003178000000000000000)
Internal Objects (node23.html#SECTION003179000000000000000)
---
guido@python.org


11.1 Standard Module cgi

node141.html
node139.html
node139.html
node1.html
node270.html
---
# 11.1 Standard Module cgi
Support module for CGI (Common Gateway Interface) scripts.
This module defines a number of utilities for use by CGI scripts
written in Python.
---
- Introduction (node141.html#SECTION0012110000000000000000)
Using the cgi module (node142.html#SECTION0012120000000000000000)
Old classes (node143.html#SECTION0012130000000000000000)
Functions (node144.html#SECTION0012140000000000000000)
Caring about security (node145.html#SECTION0012150000000000000000)
Installing your CGI script on a Unix system (node146.html#SECTION0012160000000000000000)
Testing your CGI script (node147.html#SECTION0012170000000000000000)
Debugging CGI scripts (node148.html#SECTION0012180000000000000000)
Common problems and solutions (node149.html#SECTION0012190000000000000000)
---
guido@python.org


Introduction

node142.html
node140.html
node140.html
node1.html
node270.html
---
## Introduction
A CGI script is invoked by an HTTP server, usually to process user
input submitted through an HTML <FORM> or <ISINPUT> element.
Most often, CGI scripts live in the server's special `cgi-bin'
directory. The HTTP server places all sorts of information about the
request (such as the client's hostname, the requested URL, the query
string, and lots of other goodies) in the script's shell environment,
executes the script, and sends the script's output back to the client.
The script's input is connected to the client too, and sometimes the
form data is read this way; at other times the form data is passed via
the ``query string'' part of the URL. This module (`cgi.py') is intended
to take care of the different cases and provide a simpler interface to
the Python script. It also provides a number of utilities that help
in debugging scripts, and the latest addition is support for file
uploads from a form (if your browser supports it - Grail 0.3 and
Netscape 2.0 do).
The output of a CGI script should consist of two sections, separated
by a blank line. The first section contains a number of headers,
telling the client what kind of data is following. Python code to
generate a minimal header section looks like this:
```text
print "Content-type: text/html" # HTML is following
print # blank line, end of headers
```
The second section is usually HTML, which allows the client software
to display nicely formatted text with header, in-line images, etc.
Here's Python code that prints a simple piece of HTML:
```text
print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
print "Hello, world!"
```
(It may not be fully legal HTML according to the letter of the
standard, but any browser will understand it.)
---
guido@python.org


Using the cgi module

node143.html
node140.html
node141.html
node1.html
node270.html
---
## Using the cgi module
Begin by writing import cgi. Don't use from cgi import * - the
module defines all sorts of names for its own use or for backward
compatibility that you don't want in your namespace.
It's best to use the FieldStorage class. The other classes define in this
module are provided mostly for backward compatibility. Instantiate it
exactly once, without arguments. This reads the form contents from
standard input or the environment (depending on the value of various
environment variables set according to the CGI standard). Since it may
consume standard input, it should be instantiated only once.
The FieldStorage instance can be accessed as if it were a Python
dictionary. For instance, the following code (which assumes that the
Content-type header and blank line have already been printed) checks that
the fields name and addr are both set to a non-empty string:
```text
form = cgi.FieldStorage()
form_ok = 0
if form.has_key("name") and form.has_key("addr"):
if form["name"].value != "" and form["addr"].value != "":
form_ok = 1
if not form_ok:
print "<H1>Error</H1>"
print "Please fill in the name and addr fields."
return
...further form processing here...
```
Here the fields, accessed through form[key], are themselves instances
of FieldStorage (or MiniFieldStorage, depending on the form encoding).
If the submitted form data contains more than one field with the same
name, the object retrieved by form[key] is not a (Mini)FieldStorage
instance but a list of such instances. If you expect this possibility
(i.e., when your HTML form comtains multiple fields with the same
name), use the type() function to determine whether you have a single
instance or a list of instances. For example, here's code that
concatenates any number of username fields, separated by commas:
```text
username = form["username"]
if type(username) is type([]):
# Multiple username fields specified
usernames = ""
for item in username:
if usernames:
# Next item -- insert comma
usernames = usernames + "," + item.value
else:
# First item -- don't insert comma
usernames = item.value
else:
# Single username field specified
usernames = username.value
```
If a field represents an uploaded file, the value attribute reads the
entire file in memory as a string. This may not be what you want. You can
test for an uploaded file by testing either the filename attribute or the
file attribute. You can then read the data at leasure from the file
attribute:
```text
fileitem = form["userfile"]
if fileitem.file:
# It's an uploaded file; count lines
linecount = 0
while 1:
line = fileitem.file.readline()
if not line: break
linecount = linecount + 1
```
The file upload draft standard entertains the possibility of uploading
multiple files from one field (using a recursive multipart/*
encoding). When this occurs, the item will be a dictionary-like
FieldStorage item. This can be determined by testing its type
attribute, which should have the value multipart/form-data (or
perhaps another string beginning with multipart/ It this case, it
can be iterated over recursively just like the top-level form object.
When a form is submitted in the ``old'' format (as the query string or as a
single data part of type application/x-www-form-urlencoded), the items
will actually be instances of the class MiniFieldStorage. In this case,
the list, file and filename attributes are always None.
---
node143.html
node140.html
node141.html
node1.html
node270.html
guido@python.org


Old classes

node144.html
node140.html
node142.html
node1.html
node270.html
---
## Old classes
These classes, present in earlier versions of the cgi module, are still
supported for backward compatibility. New applications should use the
FieldStorage class.
SvFormContentDict
single value form content as dictionary; assumes each
field name occurs in the form only once.
FormContentDict
multiple value form content as dictionary (the form
items are lists of values). Useful if your form contains multiple
fields with the same name.
Other classes (FormContent, InterpFormContentDict) are present for
backwards compatibility with really old applications only. If you still
use these and would be inconvenienced when they disappeared from a next
version of this module, drop me a note.
---
guido@python.org


Functions

node145.html
node140.html
node143.html
node1.html
node270.html
---
## Functions
These are useful if you want more control, or if you want to employ
some of the algorithms implemented in this module in other
circumstances.
---
node145.html
node140.html
node143.html
node1.html
node270.html
guido@python.org


Caring about security

node146.html
node140.html
node144.html
node1.html
node270.html
---
## Caring about security
There's one important rule: if you invoke an external program (e.g.
via the os.system() or os.popen() functions), make very sure you don't
pass arbitrary strings received from the client to the shell. This is
a well-known security hole whereby clever hackers anywhere on the web
can exploit a gullible CGI script to invoke arbitrary shell commands.
Even parts of the URL or field names cannot be trusted, since the
request doesn't have to come from your form!
To be on the safe side, if you must pass a string gotten from a form
to a shell command, you should make sure the string contains only
alphanumeric characters, dashes, underscores, and periods.
---
guido@python.org


node147.html
node140.html
node145.html
node1.html
node270.html
---
## Installing your CGI script on a Unix system
Read the documentation for your HTTP server and check with your local
system administrator to find the directory where CGI scripts should be
installed; usually this is in a directory `cgi-bin' in the server tree.
Make sure that your script is readable and executable by ``others''; the
Unix file mode should be 755 (use chmod 755 filename). Make sure
that the first line of the script contains #! starting in column 1
followed by the pathname of the Python interpreter, for instance:
```text
#!/usr/local/bin/python
```
Make sure the Python interpreter exists and is executable by ``others''.
Make sure that any files your script needs to read or write are
readable or writable, respectively, by ``others'' - their mode should
be 644 for readable and 666 for writable. This is because, for
security reasons, the HTTP server executes your script as user
``nobody'', without any special privileges. It can only read (write,
execute) files that everybody can read (write, execute). The current
directory at execution time is also different (it is usually the
server's cgi-bin directory) and the set of environment variables is
also different from what you get at login. in particular, don't count
on the shell's search path for executables ($PATH) or the Python
module search path ($PYTHONPATH) to be set to anything interesting.
If you need to load modules from a directory which is not on Python's
default module search path, you can change the path in your script,
before importing other modules, e.g.:
```text
import sys
sys.path.insert(0, "/usr/home/joe/lib/python")
sys.path.insert(0, "/usr/local/lib/python")
```
(This way, the directory inserted last will be searched first!)
Instructions for non-Unix systems will vary; check your HTTP server's
documentation (it will usually have a section on CGI scripts).
---
guido@python.org


Testing your CGI script

node148.html
node140.html
node146.html
node1.html
node270.html
---
## Testing your CGI script
Unfortunately, a CGI script will generally not run when you try it
from the command line, and a script that works perfectly from the
command line may fail mysteriously when run from the server. There's
one reason why you should still test your script from the command
line: if it contains a syntax error, the python interpreter won't
execute it at all, and the HTTP server will most likely send a cryptic
error to the client.
Assuming your script has no syntax errors, yet it does not work, you
have no choice but to read the next section:
---
guido@python.org


Debugging CGI scripts

node149.html
node140.html
node147.html
node1.html
node270.html
---
## Debugging CGI scripts
First of all, check for trivial installation errors - reading the
section above on installing your CGI script carefully can save you a
lot of time. If you wonder whether you have understood the
installation procedure correctly, try installing a copy of this module
file (`cgi.py') as a CGI script. When invoked as a script, the file
will dump its environment and the contents of the form in HTML form.
Give it the right mode etc, and send it a request. If it's installed
in the standard `cgi-bin' directory, it should be possible to send it a
request by entering a URL into your browser of the form:
```text
http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
```
If this gives an error of type 404, the server cannot find the script
- perhaps you need to install it in a different directory. If it
gives another error (e.g. 500), there's an installation problem that
you should fix before trying to go any further. If you get a nicely
formatted listing of the environment and form content (in this
example, the fields should be listed as ``addr'' with value ``At Home''
and ``name'' with value ``Joe Blow''), the `cgi.py' script has been
installed correctly. If you follow the same procedure for your own
script, you should now be able to debug it.
The next step could be to call the cgi module's test()
function from your script: replace its main code with the single
statement
```text
cgi.test()
```
This should produce the same results as those gotten from installing
the `cgi.py' file itself.
When an ordinary Python script raises an unhandled exception
(e.g. because of a typo in a module name, a file that can't be opened,
etc.), the Python interpreter prints a nice traceback and exits.
While the Python interpreter will still do this when your CGI script
raises an exception, most likely the traceback will end up in one of
the HTTP server's log file, or be discarded altogether.
Fortunately, once you have managed to get your script to execute
*some* code, it is easy to catch exceptions and cause a traceback to
be printed. The test() function below in this module is an example.
Here are the rules:
1. Import the traceback module (before entering the
try-except!)Make sure you finish printing the headers and the blank
line earlyAssign sys.stderr to sys.stdoutWrap all remaining code in a try-except statementIn the except clause, call traceback.print_exc()
For example:
```text
import sys
import traceback
print "Content-type: text/html"
print
sys.stderr = sys.stdout
try:
...your code here...
except:
print "\n\n<PRE>"
traceback.print_exc()
```
Notes: The assignment to sys.stderr is needed because the traceback
prints to sys.stderr.
The print "\n\n<PRE>" statement is necessary to
disable the word wrapping in HTML.
If you suspect that there may be a problem in importing the traceback
module, you can use an even more robust approach (which only uses
built-in modules):
```text
import sys
sys.stderr = sys.stdout
print "Content-type: text/plain"
print
...your code here...
```
This relies on the Python interpreter to print the traceback. The
content type of the output is set to plain text, which disables all
HTML processing. If your script works, the raw HTML will be displayed
by your client. If it raises an exception, most likely after the
first two lines have been printed, a traceback will be displayed.
Because no HTML interpretation is going on, the traceback will
readable.
---
node149.html
node140.html
node147.html
node1.html
node270.html
guido@python.org


Common problems and solutions

node150.html
node140.html
node148.html
node1.html
node270.html
---
## Common problems and solutions
- Most HTTP servers buffer the output from CGI scripts until the
script is completed. This means that it is not possible to display a
progress report on the client's display while the script is running.Check the installation instructions above.Check the HTTP server's log files. (tail -f logfile in a separate
window may be useful!)Always check a script for syntax errors first, by doing something
like python script.py.When using any of the debugging techniques, don't forget to add
import sys to the top of the script.When invoking external programs, make sure they can be found.
Usually, this means using absolute path names - $PATH is usually not
set to a very useful value in a CGI script.When reading or writing external files, make sure they can be read
or written by every user on the system.Don't try to give a CGI script a set-uid mode. This doesn't work on
most systems, and is a security liability as well.
---
guido@python.org


Modules

node16.html
node14.html
node14.html
node1.html
node270.html
---
### Modules
The only special operation on a module is attribute access:
m.name, where m is a module and name accesses
a name defined in m's symbol table. Module attributes can be
assigned to. (Note that the import statement is not, strictly
spoken, an operation on a module object; import foo does not
require a module object named foo to exist, rather it requires
an (external) definition for a module named foo
somewhere.)
A special member of every module is __dict__.
This is the dictionary containing the module's symbol table.
Modifying this dictionary will actually change the module's symbol
table, but direct assignment to the __dict__ attribute is not
possible (i.e., you can write m.__dict__['a'] = 1, which
defines m.a to be 1, but you can't write m.__dict__ = {}.
Modules are written like this: <module 'sys'>.
---
guido@python.org


11.2 Standard Module urllib

node151.html
node139.html
node149.html
node1.html
node270.html
---
# 11.2 Standard Module urllib
This module provides a high-level interface for fetching data across
the World-Wide Web. In particular, the urlopen() function is
similar to the built-in function open(), but accepts URLs
(Universal Resource Locators) instead of filenames. Some restrictions
apply -- it can only open URLs for reading, and no seek operations
are available.
It defines the following public functions:
Restrictions:
- Currently, only the following protocols are supported: HTTP, (versions
0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.
The caching feature of urlretrieve() has been disabled until I
find the time to hack proper processing of Expiration time headers.There should be a function to query whether a particular URL is in
the cache.For backward compatibility, if a URL appears to point to a local file
but the file can't be opened, the URL is re-interpreted using the FTP
protocol. This can sometimes cause confusing error messages.The urlopen() and urlretrieve() functions can cause
arbitrarily long delays while waiting for a network connection to be
set up. This means that it is difficult to build an interactive
web client using these functions without using threads.The data returned by urlopen() or urlretrieve() is the
raw data returned by the server. This may be binary data (e.g. an
image), plain text or (for example) HTML. The HTTP protocol provides
type information in the reply header, which can be inspected by
looking at the Content-type header. For the Gopher protocol,
type information is encoded in the URL; there is currently no easy way
to extract it. If the returned data is HTML, you can use the module
htmllib to parse it.
Although the urllib module contains (undocumented) routines to
parse and unparse URL strings, the recommended interface for URL
manipulation is in module urlparse.
---
node151.html
node139.html
node149.html
node1.html
node270.html
guido@python.org


11.3 Standard Module httplib

node152.html
node139.html
node150.html
node1.html
node270.html
---
# 11.3 Standard Module httplib
This module defines a class which implements the client side of the
HTTP protocol. It is normally not used directly -- the module
urllib uses it to handle URLs that use HTTP.
The module defines one class, HTTP. An HTTP instance
represents one transaction with an HTTP server. It should be
instantiated passing it a host and optional port number. If no port
number is passed, the port is extracted from the host string if it has
the form host:port, else the default HTTP port (80) is used.
If no host is passed, no connection is made, and the connect
method should be used to connect to a server. For example, the
following calls all create instances that connect to the server at the
same host and port:
```text
>>> h1 = httplib.HTTP('www.cwi.nl')
>>> h2 = httplib.HTTP('www.cwi.nl:80')
>>> h3 = httplib.HTTP('www.cwi.nl', 80)
```
Once an HTTP instance has been connected to an HTTP server, it
should be used as follows:
---
- HTTP Objects (node152.html#SECTION0012310000000000000000)
Example (node153.html#SECTION0012320000000000000000)
---
guido@python.org


HTTP Objects

node153.html
node151.html
node151.html
node1.html
node270.html
---
## HTTP Objects
HTTP instances have the following methods:
---
node153.html
node151.html
node151.html
node1.html
node270.html
guido@python.org


Example

node154.html
node151.html
node152.html
node1.html
node270.html
---
## Example
Here is an example session:
```text
>>> import httplib
>>> h = httplib.HTTP('www.cwi.nl')
>>> h.putrequest('GET', '/index.html')
>>> h.putheader('Accept', 'text/html')
>>> h.putheader('Accept', 'text/plain')
>>> h.endheaders()
>>> errcode, errmsg, headers = h.getreply()
>>> print errcode # Should be 200
>>> f = h.getfile()
>>> data = f.read() # Get the raw HTML
>>> f.close()
>>>
```
---
guido@python.org


11.4 Standard Module ftplib

node155.html
node139.html
node153.html
node1.html
node270.html
---
# 11.4 Standard Module ftplib
This module defines the class FTP and a few related items. The
FTP class implements the client side of the FTP protocol. You
can use this to write Python programs that perform a variety of
automated FTP jobs, such as mirroring other ftp servers. It is also
used by the module urllib to handle URLs that use FTP. For
more information on FTP (File Transfer Protocol), see Internet RFC 959.
Here's a sample session using the ftplib module:
```text
>>> from ftplib import FTP
>>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
>>> ftp.login() # user anonymous, passwd user@hostname
>>> ftp.retrlines('LIST') # list directory contents
total 24418
drwxrwsr-x 5 ftp-usr pdmaint 1536 Mar 20 09:48 .
dr-xr-srwt 105 ftp-usr pdmaint 1536 Mar 21 14:32 ..
-rw-r--r-- 1 ftp-usr pdmaint 5305 Mar 20 09:48 INDEX
.
.
.
>>> ftp.quit()
```
The module defines the following items:
---
- FTP Objects (node155.html#SECTION0012410000000000000000)
---
guido@python.org


FTP Objects

node156.html
node154.html
node154.html
node1.html
node270.html
---
## FTP Objects
FTP instances have the following methods:
---
node156.html
node154.html
node154.html
node1.html
node270.html
guido@python.org


11.5 Standard Module gopherlib

node157.html
node139.html
node155.html
node1.html
node270.html
---
# 11.5 Standard Module gopherlib
This module provides a minimal implementation of client side of the
the Gopher protocol. It is used by the module urllib to handle
URLs that use the Gopher protocol.
The module defines the following functions:
Note that the data returned by the Gopher server can be of any type,
depending on the first character of the selector string. If the data
is text (first character of the selector is `0'), lines are
terminated by CRLF, and the data is terminated by a line consisting of
a single `.', and a leading `.' should be stripped from
lines that begin with `..'. Directory listings (first character
of the selector is `1') are transferred using the same protocol.
---
guido@python.org


11.6 Standard Module nntplib

node158.html
node139.html
node156.html
node1.html
node270.html
---
# 11.6 Standard Module nntplib
This module defines the class NNTP which implements the client
side of the NNTP protocol. It can be used to implement a news reader
or poster, or automated news processors. For more information on NNTP
(Network News Transfer Protocol), see Internet RFC 977.
Here are two small examples of how it can be used. To list some
statistics about a newsgroup and print the subjects of the last 10
articles:
```text
>>> s = NNTP('news.cwi.nl')
>>> resp, count, first, last, name = s.group('comp.lang.python')
>>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
Group comp.lang.python has 59 articles, range 3742 to 3803
>>> resp, subs = s.xhdr('subject', first + '-' + last)
>>> for id, sub in subs[-10:]: print id, sub
...
3792 Re: Removing elements from a list while iterating...
3793 Re: Who likes Info files?
3794 Emacs and doc strings
3795 a few questions about the Mac implementation
3796 Re: executable python scripts
3797 Re: executable python scripts
3798 Re: a few questions about the Mac implementation
3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules
3802 Re: executable python scripts
3803 Re: \POSIX{} wait and SIGCHLD
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
>>>
```
To post an article from a file (this assumes that the article has
valid headers):
```text
>>> s = NNTP('news.cwi.nl')
>>> f = open('/tmp/article')
>>> s.post(f)
'240 Article posted successfully.'
>>> s.quit()
'205 news.cwi.nl closing connection. Goodbye.'
>>>
```
The module itself defines the following items:
---
- NNTP Objects (node158.html#SECTION0012610000000000000000)
---
guido@python.org


NNTP Objects

node159.html
node157.html
node157.html
node1.html
node270.html
---
## NNTP Objects
NNTP instances have the following methods. The response that is
returned as the first item in the return tuple of almost all methods
is the server's response: a string beginning with a three-digit code.
If the server's response indicates an error, the method raises one of
the above exceptions.
---
node159.html
node157.html
node157.html
node1.html
node270.html
guido@python.org


11.7 Standard Module urlparse

node160.html
node139.html
node158.html
node1.html
node270.html
---
# 11.7 Standard Module urlparse
This module defines a standard interface to break URL strings up in
components (addessing scheme, network location, path etc.), to combine
the components back into a URL string, and to convert a ``relative
URL'' to an absolute URL given a ``base URL''.
The module has been designed to match the Internet RFC on Relative
Uniform Resource Locators (and discovered a bug in an earlier
draft!). Refer to RFC 1808 for details on relative
URLs and RFC 1738 for information on basic URL syntax.
It defines the following functions:
---
node160.html
node139.html
node158.html
node1.html
node270.html
guido@python.org


Classes and Class Instances

node17.html
node14.html
node15.html
node1.html
node270.html
---
### Classes and Class Instances
See Chapters 3 and 7 of the Python Reference Manual for these.
---
guido@python.org


11.8 Standard Module sgmllib

node161.html
node139.html
node159.html
node1.html
node270.html
---
# 11.8 Standard Module sgmllib
This module defines a class SGMLParser which serves as the
basis for parsing text files formatted in SGML (Standard Generalized
Mark-up Language). In fact, it does not provide a full SGML parser
-- it only parses SGML insofar as it is used by HTML, and the module
only exists as a base for the htmllib module.
In particular, the parser is hardcoded to recognize the following
constructs:
- Opening and closing tags of the form
`<tag attr="value" ...>' and
`</tag>', respectively.Numeric character references of the form `&#name;'.Entity references of the form `&name;'.SGML comments of the form `<!-text->'. Note that
spaces, tabs, and newlines are allowed between the trailing
`>' and the immediately preceeding `-'.
The SGMLParser class must be instantiated without arguments.
It has the following interface methods:
Apart from overriding or extending the methods listed above, derived
classes may also define methods of the following form to define
processing of specific tags. Tag names in the input stream are case
independent; the tag occurring in method names must be in lower
case:
Note that the parser maintains a stack of open elements for which no
end tag has been found yet. Only tags processed by
start_tag() are pushed on this stack. Definition of an
end_tag() method is optional for these tags. For tags
processed by do_tag() or by unknown_tag(), no
end_tag() method must be defined; if defined, it will not
be used. If both start_tag() and do_tag()
methods exist for a tag, the start_tag() method takes
precedence.
---
node161.html
node139.html
node159.html
node1.html
node270.html
guido@python.org


11.9 Standard Module htmllib

node162.html
node139.html
node160.html
node1.html
node270.html
---
# 11.9 Standard Module htmllib
This module defines a class which can serve as a base for parsing text
files formatted in the HyperText Mark-up Language (HTML). The class
is not directly concerned with I/O -- it must be provided with input
in string form via a method, and makes calls to methods of a
``formatter'' object in order to produce output. The
HTMLParser class is designed to be used as a base class for
other classes in order to add functionality, and allows most of its
methods to be extended or overridden. In turn, this class is derived
from and extends the SGMLParser class defined in module
sgmllib. The HTMLParser
implementation supports the HTML 2.0 language as described in
RFC 1866. Two implementations of formatter objects are provided in
the formatter module; refer to the
documentation for that module for information on the formatter
interface.
The following is a summary of the interface defined by
sgmllib.SGMLParser:
- The interface to feed data to an instance is through the feed()
method, which takes a string argument. This can be called with as
little or as much text at a time as desired; `p.feed(a);
p.feed(b)' has the same effect as `p.feed(a+b)'. When the data
contains complete HTML tags, these are processed immediately;
incomplete elements are saved in a buffer. To force processing of all
unprocessed data, call the close() method.
For example, to parse the entire contents of a file, use:
```text
parser.feed(open('myfile.html').read())
parser.close()
```
The interface to define semantics for HTML tags is very simple: derive
a class and define methods called start_tag(),
end_tag(), or do_tag(). The parser will
call these at appropriate moments: start_tag or
do_tag() is called when an opening tag of the form
<tag ...> is encountered; end_tag() is called
when a closing tag of the form <tag> is encountered. If
an opening tag requires a corresponding closing tag, like <H1>
... </H1>, the class should define the start_tag()
method; if a tag requires no closing tag, like <P>, the class
should define the do_tag() method.
The module defines a single class:
In addition to tag methods, the HTMLParser class provides some
additional methods and instance variables for use within tag methods.
---
node162.html
node139.html
node160.html
node1.html
node270.html
guido@python.org


11.10 Standard Module xmllib

node163.html
node139.html
node161.html
node1.html
node270.html
---
# 11.10 Standard Module xmllib
This module defines a class XMLParser which serves as the basis
for parsing text files formatted in XML (eXtended Markup Language).
The XMLParser class must be instantiated without arguments. It
has the following interface methods:
Apart from overriding or extending the methods listed above, derived
classes may also define methods and variables of the following form to
define processing of specific tags. Tag names in the input stream are
case dependent; the tag occurring in method names must be in the
correct case:
---
node163.html
node139.html
node161.html
node1.html
node270.html
guido@python.org


11.11 Standard Module formatter

node164.html
node139.html
node162.html
node1.html
node270.html
---
# 11.11 Standard Module formatter
This module supports two interface definitions, each with mulitple
implementations. The formatter interface is used by the
HTMLParser class of the htmllib module, and the
writer interface is required by the formatter interface.
Formatter objects transform an abstract flow of formatting events into
specific output events on writer objects. Formatters manage several
stack structures to allow various properties of a writer object to be
changed and restored; writers need not be able to handle relative
changes nor any sort of ``change back'' operation. Specific writer
properties which may be controlled via formatter objects are
horizontal alignment, font, and left margin indentations. A mechanism
is provided which supports providing arbitrary, non-exclusive style
settings to a writer as well. Additional interfaces facilitate
formatting events which are not reversible, such as paragraph
separation.
Writer objects encapsulate device interfaces. Abstract devices, such
as file formats, are supported as well as physical devices. The
provided implementations all work with abstract devices. The
interface makes available mechanisms for setting the properties which
formatter objects manage and inserting data into the output.
---
- The Formatter Interface (node164.html#SECTION00121110000000000000000)
Formatter Implementations (node165.html#SECTION00121120000000000000000)
The Writer Interface (node166.html#SECTION00121130000000000000000)
Writer Implementations (node167.html#SECTION00121140000000000000000)
---
guido@python.org


The Formatter Interface

node165.html
node163.html
node163.html
node1.html
node270.html
---
## The Formatter Interface
Interfaces to create formatters are dependent on the specific
formatter class being instantiated. The interfaces described below
are the required interfaces which all formatters must support once
initialized.
One data element is defined at the module level:
The following attributes are defined for formatter instance objects:
---
node165.html
node163.html
node163.html
node1.html
node270.html
guido@python.org


Formatter Implementations

node166.html
node163.html
node164.html
node1.html
node270.html
---
## Formatter Implementations
Two implementations of formatter objects are provided by this module.
Most applications may use one of these classes without modification or
subclassing.
---
guido@python.org


The Writer Interface

node167.html
node163.html
node165.html
node1.html
node270.html
---
## The Writer Interface
Interfaces to create writers are dependent on the specific writer
class being instantiated. The interfaces described below are the
required interfaces which all writers must support once initialized.
Note that while most applications can use the AbstractFormatter
class as a formatter, the writer must typically be provided by the
application.
---
node167.html
node163.html
node165.html
node1.html
node270.html
guido@python.org


Writer Implementations

node168.html
node163.html
node166.html
node1.html
node270.html
---
## Writer Implementations
Three implementations of the writer object interface are provided as
examples by this module. Most applications will need to derive new
writer classes from the NullWriter class.
---
guido@python.org


11.12 Standard Module rfc822

node169.html
node139.html
node167.html
node1.html
node270.html
---
# 11.12 Standard Module rfc822
This module defines a class, Message, which represents a
collection of ``email headers'' as defined by the Internet standard
RFC 822. It is used in various contexts, usually to read such
headers from a file.
Note that there's a separate module to read Unix, MH, and MMDF
style mailbox files: mailbox.
A Message instance is instantiated with an open file object as
parameter. The optional seekable parameter indicates if the
file object is seekable; the default value is 1 for true.
Instantiation reads headers from the file up to a blank line and
stores them in the instance; after instantiation, the file is
positioned directly after the blank line that terminates the headers.
Input lines as read from the file may either be terminated by CR-LF or
by a single linefeed; a terminating CR-LF is replaced by a single
linefeed before the line is stored.
All header matching is done independent of upper or lower case;
e.g. m['From'], m['from'] and m['FROM'] all yield
the same result.
---
- Message Objects (node169.html#SECTION00121210000000000000000)
---
node169.html
node139.html
node167.html
node1.html
node270.html
guido@python.org


Message Objects

node170.html
node168.html
node168.html
node1.html
node270.html
---
## Message Objects
A Message instance has the following methods:
Message instances also support a read-only mapping interface.
In particular: m[name] is the same as m.getheader(name);
and len(m), m.has_key(name), m.keys(),
m.values() and m.items() act as expected (and
consistently).
Finally, Message instances have two public instance variables:
---
node170.html
node168.html
node168.html
node1.html
node270.html
guido@python.org


Functions

node18.html
node14.html
node16.html
node1.html
node270.html
---
### Functions
Function objects are created by function definitions. The only
operation on a function object is to call it:
func(argument-list).
There are really two flavors of function objects: built-in functions
and user-defined functions. Both support the same operation (to call
the function), but the implementation is different, hence the
different object types.
The implementation adds two special read-only attributes:
f.func_code is a function's code object (see below) and
f.func_globals is the dictionary used as the function's
global name space (this is the same as m.__dict__ where
m is the module in which the function f was defined).
---
guido@python.org


11.13 Standard Module mimetools

node171.html
node139.html
node169.html
node1.html
node270.html
---
# 11.13 Standard Module mimetools
This module defines a subclass of the class rfc822.Message and
a number of utility functions that are useful for the manipulation for
MIME style multipart or encoded message.
It defines the following items:
---
- Additional Methods of Message objects (node171.html#SECTION00121310000000000000000)
---
guido@python.org


Additional Methods of Message objects

node172.html
node170.html
node170.html
node1.html
node270.html
---
## Additional Methods of Message objects
The mimetools.Message class defines the following methods in
addition to the rfc822.Message class:
---
guido@python.org


11.14 Standard Module binhex

node173.html
node139.html
node171.html
node1.html
node270.html
---
# 11.14 Standard Module binhex
This module encodes and decodes files in binhex4 format, a format
allowing representation of Macintosh files in ASCII. On the macintosh,
both forks of a file and the finder information are encoded (or
decoded), on other platforms only the data fork is handled.
The binhex module defines the following functions:
---
- Notes (node173.html#SECTION00121410000000000000000)
---
guido@python.org


Notes

node174.html
node172.html
node172.html
node1.html
node270.html
---
## Notes
There is an alternative, more powerful interface to the coder and
decoder, see the source for details.
If you code or decode textfiles on non-Macintosh platforms they will
still use the macintosh newline convention (carriage-return as end of
line).
As of this writing, hexbin appears to not work in all cases.
---
guido@python.org


11.15 Standard Module uu

node175.html
node139.html
node173.html
node1.html
node270.html
---
# 11.15 Standard Module uu
This module encodes and decodes files in uuencode format, allowing
arbitrary binary data to be transferred over ascii-only connections.
Wherever a file argument is expected, the methods accept a file-like
object. For backwards compatibility, a string containing a pathname
is also accepted, and the corresponding file will be opened for
reading and writing; the pathname '-' is understood to mean the
standard input or output. However, this interface is deprecated; it's
better for the caller to open the file itself, and be sure that, when
required, the mode is 'rb' or 'wb' on Windows or DOS.
This code was contributed by Lance Ellinghouse, and modified by Jack
Jansen.
The uu module defines the following functions:
---
guido@python.org


11.16 Built-in Module binascii

node176.html
node139.html
node174.html
node1.html
node270.html
---
# 11.16 Built-in Module binascii
The binascii module contains a number of methods to convert between
binary and various ascii-encoded binary representations. Normally, you
will not use these modules directly but use wrapper modules like
uu or hexbin in stead, this module solely exists because
bit-manipuation of large amounts of data is slow in python.
The binascii module defines the following functions:
---
node176.html
node139.html
node174.html
node1.html
node270.html
guido@python.org


11.17 Standard Module xdrlib

node177.html
node139.html
node175.html
node1.html
node270.html
---
# 11.17 Standard Module xdrlib
The xdrlib module supports the External Data Representation
Standard as described in RFC 1014, written by Sun Microsystems,
Inc. June 1987. It supports most of the data types described in the
RFC.
The xdrlib module defines two classes, one for packing
variables into XDR representation, and another for unpacking from XDR
representation. There are also two exception classes.
---
- Packer Objects (node177.html#SECTION00121710000000000000000)
Unpacker Objects (node178.html#SECTION00121720000000000000000)
Exceptions (node179.html#SECTION00121730000000000000000)
---
guido@python.org


Packer Objects

node178.html
node176.html
node176.html
node1.html
node270.html
---
## Packer Objects
Packer is the class for packing data into XDR representation.
The Packer class is instantiated with no arguments.
In general, you can pack any of the most common XDR data types by
calling the appropriate pack_type() method. Each method
takes a single argument, the value to pack. The following simple data
type packing methods are supported: pack_uint(), pack_int(),
pack_enum(), pack_bool(), pack_uhyper(),
and pack_hyper().
The following methods support packing strings, bytes, and opaque data:
The following methods support packing arrays and lists:
---
node178.html
node176.html
node176.html
node1.html
node270.html
guido@python.org


Unpacker Objects

node179.html
node176.html
node177.html
node1.html
node270.html
---
## Unpacker Objects
Unpacker is the complementary class which unpacks XDR data
values from a string buffer, and has the following methods:
In addition, every data type that can be packed with a Packer,
can be unpacked with an Unpacker. Unpacking methods are of the
form unpack_type(), and take no arguments. They return the
unpacked object.
In addition, the following methods unpack strings, bytes, and opaque
data:
The following methods support unpacking arrays and lists:
---
node179.html
node176.html
node177.html
node1.html
node270.html
guido@python.org


Exceptions

node180.html
node176.html
node178.html
node1.html
node270.html
---
## Exceptions
Exceptions in this module are coded as class instances:
Here is an example of how you would catch one of these exceptions:
```text
import xdrlib
p = xdrlib.Packer()
try:
p.pack_double(8.01)
except xdrlib.ConversionError, instance:
print 'packing the double failed:', instance.msg
```
---
guido@python.org


Methods

node19.html
node14.html
node17.html
node1.html
node270.html
---
### Methods
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods (such as append() on
lists) and class instance methods. Built-in methods are described
with the types that support them.
The implementation adds two special read-only attributes to class
instance methods: m.im_self is the object whose method this
is, and m.im_func is the function implementing the method.
Calling m(arg-1, arg-2, ...,
arg-n) is completely equivalent to calling
m.im_func(m.im_self, arg-1, arg-2,
..., arg-n).
See the Python Reference Manual for more information.
---
guido@python.org


11.18 Standard Module mailcap

node181.html
node139.html
node179.html
node1.html
node270.html
---
# 11.18 Standard Module mailcap
Mailcap files are used to configure how MIME-aware applications such
as mail readers and Web browsers react to files with different MIME
types. (The name ``mailcap'' is derived from the phrase ``mail
capability''.) For example, a mailcap file might contain a line like
`video/mpeg; xmpeg %s'. Then, if the user encounters an email
message or Web document with the MIME type video/mpeg, %s will be
replaced by a filename (usually one belonging to a temporary file) and
the xmpeg program can be automatically started to view the file.
The mailcap format is documented in RFC 1524, ``A User Agent
Configuration Mechanism For Multimedia Mail Format Information,'' but
is not an Internet standard. However, mailcap files are supported on
most Unix systems.
An example usage:
```text
>>> import mailcap
>>> d=mailcap.getcaps()
>>> mailcap.findmatch(d, 'video/mpeg', filename='/tmp/tmp1223')
('xmpeg /tmp/tmp1223', {'view': 'xmpeg %s'})
```
---
node181.html
node139.html
node179.html
node1.html
node270.html
guido@python.org


11.19 Standard Module base64

node182.html
node139.html
node180.html
node1.html
node270.html
---
# 11.19 Standard Module base64
This module perform base-64 encoding and decoding of arbitrary binary
strings into text strings that can be safely emailed or posted. The
encoding scheme is defined in RFC 1421 and is used for MIME email and
various other Internet-related applications; it is not the same as the
output produced by the `uuencode' program. For example, the
string 'www.python.org' is encoded as the string
'd3d3LnB5dGhvbi5vcmc=\n'.
---
guido@python.org


11.20 Standard Module quopri

node183.html
node139.html
node181.html
node1.html
node270.html
---
# 11.20 Standard Module quopri
This module performs quoted-printable transport encoding and decoding,
as defined in RFC 1521: ``MIME (Multipurpose Internet Mail Extensions)
Part One''. The quoted-printable encoding is designed for data where
there are relatively few nonprintable characters; the base-64 encoding
scheme available via the base64 module is more compact if there
are many such characters, as when sending a graphics file.
---
guido@python.org


11.21 Standard Module SocketServer

node184.html
node139.html
node182.html
node1.html
node270.html
---
# 11.21 Standard Module SocketServer
The SocketServer module simplifies the task of writing network
servers.
There are four basic server classes: TCPServer uses the
Internet TCP protocol, which provides for continuous streams of data
between the client and server. UDPServer uses datagrams, which
are discrete packets of information that may arrive out of order or be
lost while in transit. The more infrequently used
UnixStreamServer and UnixDatagramServer classes are
similar, but use Unix domain sockets; they're not available on
non-Unix platforms. For more details on network programming, consult
a book such as W. Richard Steven's UNIX Network Programming
or Ralph Davis's Win32 Network Programming.
These four classes process requests synchronously; each request
must be completed before the next request can be started. This isn't
suitable if each request takes a long time to complete, because it
requires a lot of computation, or because it returns a lot of data
which the client is slow to process. The solution is to create a
separate process or thread to handle each request; the
ForkingMixIn and ThreadingMixIn mix-in classes can be
used to support asynchronous behaviour.
Creating a server requires several steps. First, you must create a
request handler class by subclassing the BaseRequestHandler
class and overriding its handle() method; this method will
process incoming requests. Second, you must instantiate one of the
server classes, passing it the server's address and the request
handler class. Finally, call the handle_request() or
serve_forever() method of the server object to process one or
many requests.
Server classes have the same external methods and attributes, no
matter what network protocol they use:
The server classes support the following class variables:
There are various server methods that can be overridden by subclasses
of base server classes like TCPServer; these methods aren't
useful to external users of the server object.
The request handler class must define a new handle method, and
can override any of the following methods. A new instance is created
for each request.
---
node184.html
node139.html
node182.html
node1.html
node270.html
guido@python.org


11.22 Standard Module mailbox

node185.html
node139.html
node183.html
node1.html
node270.html
---
# 11.22 Standard Module mailbox
This module defines a number of classes that allow easy and uniform
access to mail messages in a (unix) mailbox.
---
- Mailbox Objects (node185.html#SECTION00122210000000000000000)
---
guido@python.org


Mailbox Objects

node186.html
node184.html
node184.html
node1.html
node270.html
---
## Mailbox Objects
All implementations of Mailbox objects have one externally visible
method:
---
guido@python.org


11.23 Standard Module mimify

node187.html
node139.html
node185.html
node1.html
node270.html
---
# 11.23 Standard Module mimify
The mimify module defines two functions to convert mail messages to
and from MIME format. The mail message can be either a simple message
or a so-called multipart message. Each part is treated separately.
Mimifying (a part of) a message entails encoding the message as
quoted-printable if it contains any characters that cannot be
represented using 7-bit ASCII. Unmimifying (a part of) a message
entails undoing the quoted-printable encoding. Mimify and unmimify
are especially useful when a message has to be edited before being
sent. Typical use would be:
```text
unmimify message
edit message
mimify message
send message
```
The modules defines the following user-callable functions and
user-settable variables:
This module can also be used from the command line. Usage is as
follows:
```text
mimify.py -e [-l length] [infile [outfile]]
mimify.py -d [-b] [infile [outfile]]
```
to encode (mimify) and decode (unmimify) respectively. infile
defaults to standard input, outfile defaults to standard output.
The same file can be specified for input and output.
If the -l option is given when encoding, if there are any lines
longer than the specified length, the containing part will be
encoded.
If the -b option is given when decoding, any base64 parts will
be decoded as well.
---
node187.html
node139.html
node185.html
node1.html
node270.html
guido@python.org


11.24 Standard Module BaseHTTPServer

node188.html
node139.html
node186.html
node1.html
node270.html
---
# 11.24 Standard Module BaseHTTPServer
This module defines two classes for implementing HTTP servers
(web servers). Usually, this module isn't used directly, but is used
as a basis for building functioning web servers. See the
SimpleHTTPServer and CGIHTTPServer modules.
The first class, HTTPServer, is a SocketServer.TCPServer
subclass. It creates and listens at the web socket, dispatching the
requests to a handler. Code to create and run the server looks like
this:
```text
def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
```
The HTTPServer class builds on the TCPServer class by
storing the server address as instance
variables named server_name and server_port. The
server is accessible by the handler, typically through the handler's
server instance variable.
The module's second class, BaseHTTPRequestHandler, is used
to handle the HTTP requests that arrive at the server. By itself,
it cannot respond to any actual HTTP requests; it must be subclassed
to handle each request method (e.g. GET or POST).
BaseHTTPRequestHandler provides a number of class and instance
variables, and methods for use by subclasses.
The handler will parse the request and the headers, then call a
method specific to the request type. The method name is constructed
from the request. For example, for the request SPAM, the
do_SPAM method will be called with no arguments. All of
the relevant information is stored into instance variables of the
handler.
BaseHTTPRequestHandler has the following instance variables:
BaseHTTPRequestHandler has the following class variables:
A BaseHTTPRequestHandler instance has the following methods:
---
node188.html
node139.html
node186.html
node1.html
node270.html
guido@python.org


12 Restricted Execution

node189.html
lib.html
node187.html
node1.html
node270.html
---
# 12 Restricted Execution
In general, Python programs have complete access to the underlying
operating system throug the various functions and classes, For
example, a Python program can open any file for reading and writing by
using the open() built-in function (provided the underlying OS
gives you permission!). This is exactly what you want for most
applications.
There exists a class of applications for which this ``openness'' is
inappropriate. Take Grail: a web browser that accepts ``applets'',
snippets of Python code, from anywhere on the Internet for execution
on the local system. This can be used to improve the user interface
of forms, for instance. Since the originator of the code is unknown,
it is obvious that it cannot be trusted with the full resources of the
local machine.
Restricted execution is the basic framework in Python that allows
for the segregation of trusted and untrusted code. It is based on the
notion that trusted Python code (a supervisor) can create a
``padded cell' (or environment) with limited permissions, and run the
untrusted code within this cell. The untrusted code cannot break out
of its cell, and can only interact with sensitive system resources
through interfaces defined and managed by the trusted code. The term
``restricted execution'' is favored over ``safe-Python''
since true safety is hard to define, and is determined by the way the
restricted environment is created. Note that the restricted
environments can be nested, with inner cells creating subcells of
lesser, but never greater, privilege.
An interesting aspect of Python's restricted execution model is that
the interfaces presented to untrusted code usually have the same names
as those presented to trusted code. Therefore no special interfaces
need to be learned to write code designed to run in a restricted
environment. And because the exact nature of the padded cell is
determined by the supervisor, different restrictions can be imposed,
depending on the application. For example, it might be deemed
``safe'' for untrusted code to read any file within a specified
directory, but never to write a file. In this case, the supervisor
may redefine the built-in
open() function so that it raises an exception whenever the
mode parameter is 'w'. It might also perform a
chroot()-like operation on the filename parameter, such
that root is always relative to some safe ``sandbox'' area of the
filesystem. In this case, the untrusted code would still see an
built-in open() function in its environment, with the same
calling interface. The semantics would be identical too, with
IOErrors being raised when the supervisor determined that an
unallowable parameter is being used.
The Python run-time determines whether a particular code block is
executing in restricted execution mode based on the identity of the
__builtins__ object in its global variables: if this is (the
dictionary of) the standard __builtin__ module, the code is
deemed to be unrestricted, else it is deemed to be restricted.
Python code executing in restricted mode faces a number of limitations
that are designed to prevent it from escaping from the padded cell.
For instance, the function object attribute func_globals and the
class and instance object attribute __dict__ are unavailable.
Two modules provide the framework for setting up restricted execution
environments:
---
- 12.1 Standard Module rexec (node189.html#SECTION0013100000000000000000)
- An example (node190.html#SECTION0013110000000000000000)
12.2 Standard Module Bastion (node191.html#SECTION0013200000000000000000)
---
node189.html
lib.html
node187.html
node1.html
node270.html
guido@python.org


12.1 Standard Module rexec

node190.html
node188.html
node188.html
node1.html
node270.html
---
# 12.1 Standard Module rexec
This module contains the RExec class, which supports
r_exec(), r_eval(), r_execfile(), and
r_import() methods, which are restricted versions of the standard
Python functions exec(), eval(), execfile(), and
the import statement.
Code executed in this restricted environment will
only have access to modules and functions that are deemed safe; you
can subclass RExec to add or remove capabilities as desired.
Note: The RExec class can prevent code from performing
unsafe operations like reading or writing disk files, or using TCP/IP
sockets. However, it does not protect against code using extremely
large amounts of memory or CPU time.
The RExec class has the following class attributes, which are
used by the __init__() method. Changing them on an existing
instance won't have any effect; instead, create a subclass of
RExec and assign them new values in the class definition.
Instances of the new class will then use those new values. All these
attributes are tuples of strings.
RExec instances support the following methods:
Methods whose names begin with s_ are similar to the functions
beginning with r_, but the code will be granted access to
restricted versions of the standard I/O streans sys.stdin,
sys.stderr, and sys.stdout.
RExec objects must also support various methods which will be
implicitly called by code executing in the restricted environment.
Overriding these methods in a subclass is used to change the policies
enforced by a restricted environment.
And their equivalents with access to restricted standard I/O streams:
---
- An example (node190.html#SECTION0013110000000000000000)
---
node190.html
node188.html
node188.html
node1.html
node270.html
guido@python.org


Code Objects

node20.html
node14.html
node18.html
node1.html
node270.html
---
### Code Objects
Code objects are used by the implementation to represent
``pseudo-compiled'' executable Python code such as a function body.
They differ from function objects because they don't contain a
reference to their global execution environment. Code objects are
returned by the built-in compile() function and can be
extracted from function objects through their func_code
attribute.
A code object can be executed or evaluated by passing it (instead of a
source string) to the exec statement or the built-in
eval() function.
See the Python Reference Manual for more information.
---
guido@python.org


An example

node191.html
node189.html
node189.html
node1.html
node270.html
---
## An example
Let us say that we want a slightly more relaxed policy than the
standard RExec class. For example, if we're willing to allow
files in `/tmp' to be written, we can subclass the RExec
class:
```text
class TmpWriterRExec(rexec.RExec):
def r_open(self, file, mode='r', buf=-1):
if mode in ('r', 'rb'):
pass
elif mode in ('w', 'wb', 'a', 'ab'):
# check filename : must begin with /tmp/
if file[:5]!='/tmp/':
raise IOError, "can't write outside /tmp"
elif (string.find(file, '/../') >= 0 or
file[:3] == '../' or file[-3:] == '/..'):
raise IOError, "'..' in filename forbidden"
else: raise IOError, "Illegal open() mode"
return open(file, mode, buf)
```
Notice that the above code will occasionally forbid a perfectly valid
filename; for example, code in the restricted environment won't be
able to open a file called `/tmp/foo/../bar'. To fix this, the
r_open method would have to simplify the filename to
`/tmp/bar', which would require splitting apart the filename and
performing various operations on it. In cases where security is at
stake, it may be preferable to write simple code which is sometimes
overly restrictive, instead of more general code that is also more
complex and may harbor a subtle security hole.
---
guido@python.org


12.2 Standard Module Bastion

node192.html
node188.html
node190.html
node1.html
node270.html
---
# 12.2 Standard Module Bastion
According to the dictionary, a bastion is ``a fortified area or
position'', or ``something that is considered a stronghold.'' It's a
suitable name for this module, which provides a way to forbid access
to certain attributes of an object. It must always be used with the
rexec module, in order to allow restricted-mode programs access
to certain safe attributes of an object, while denying access to
other, unsafe attributes.
---
guido@python.org


13 Multimedia Services

node193.html
lib.html
node191.html
node1.html
node270.html
---
# 13 Multimedia Services
The modules described in this chapter implement various algorithms or
interfaces that are mainly useful for multimedia applications. They
are available at the discretion of the installation. Here's an overview:
---
- 13.1 Built-in Module audioop (node193.html#SECTION0014100000000000000000)
13.2 Built-in Module imageop (node194.html#SECTION0014200000000000000000)
13.3 Standard Module aifc (node195.html#SECTION0014300000000000000000)
13.4 Built-in Module jpeg (node196.html#SECTION0014400000000000000000)
13.5 Built-in Module rgbimg (node197.html#SECTION0014500000000000000000)
13.6 Standard Module imghdr (node198.html#SECTION0014600000000000000000)
---
guido@python.org


13.1 Built-in Module audioop

node194.html
node192.html
node192.html
node1.html
node270.html
---
# 13.1 Built-in Module audioop
The audioop module contains some useful operations on sound fragments.
It operates on sound fragments consisting of signed integer samples
8, 16 or 32 bits wide, stored in Python strings. This is the same
format as used by the al and sunaudiodev modules. All
scalar items are integers, unless specified otherwise.
A few of the more complicated operations only take 16-bit samples,
otherwise the sample size (in bytes) is always a parameter of the operation.
The module defines the following variables and functions:
Note that operations such as mul or max make no
distinction between mono and stereo fragments, i.e. all samples are
treated equal. If this is a problem the stereo fragment should be split
into two mono fragments first and recombined later. Here is an example
of how to do that:
```text
def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
lsample = audioop.mul(sample, width, lfactor)
rsample = audioop.mul(sample, width, rfactor)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
```
If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e. to be able to tolerate packet loss)
you should not only transmit the data but also the state. Note that
you should send the initial state (the one you passed to
lin2adpcm) along to the decoder, not the final state (as returned by
the coder). If you want to use struct to store the state in
binary you can code the first element (the predicted value) in 16 bits
and the second (the delta index) in 8.
The ADPCM coders have never been tried against other ADPCM coders,
only against themselves. It could well be that I misinterpreted the
standards in which case they will not be interoperable with the
respective standards.
The find... routines might look a bit funny at first sight.
They are primarily meant to do echo cancellation. A reasonably
fast way to do this is to pick the most energetic piece of the output
sample, locate that in the input sample and subtract the whole output
sample from the input sample:
```text
def echocancel(outputdata, inputdata):
pos = audioop.findmax(outputdata, 800) # one tenth second
out_test = outputdata[pos*2:]
in_test = inputdata[pos*2:]
ipos, factor = audioop.findfit(in_test, out_test)
# Optional (for better cancellation):
# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
# out_test)
prefill = '\0'*(pos+ipos)*2
postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
return audioop.add(inputdata, outputdata, 2)
```
---
node194.html
node192.html
node192.html
node1.html
node270.html
guido@python.org


13.2 Built-in Module imageop

node195.html
node192.html
node193.html
node1.html
node270.html
---
# 13.2 Built-in Module imageop
The imageop module contains some useful operations on images.
It operates on images consisting of 8 or 32 bit pixels
stored in Python strings. This is the same format as used
by gl.lrectwrite and the imgfile module.
The module defines the following variables and functions:
---
node195.html
node192.html
node193.html
node1.html
node270.html
guido@python.org


13.3 Standard Module aifc

node196.html
node192.html
node194.html
node1.html
node270.html
---
# 13.3 Standard Module aifc
This module provides support for reading and writing AIFF and AIFF-C
files. AIFF is Audio Interchange File Format, a format for storing
digital audio samples in a file. AIFF-C is a newer version of the
format that includes the ability to compress the audio data.
Audio files have a number of parameters that describe the audio data.
The sampling rate or frame rate is the number of times per second the
sound is sampled. The number of channels indicate if the audio is
mono, stereo, or quadro. Each frame consists of one sample per
channel. The sample size is the size in bytes of each sample. Thus a
frame consists of nchannels*samplesize bytes, and a
second's worth of audio consists of
nchannels*samplesize*framerate bytes.
For example, CD quality audio has a sample size of two bytes (16
bits), uses two channels (stereo) and has a frame rate of 44,100
frames/second. This gives a frame size of 4 bytes (2*2), and a
second's worth occupies 2*2*44100 bytes, i.e. 176,400 bytes.
Module aifc defines the following function:
Objects returned by aifc.open() when a file is opened for
reading have the following methods:
Objects returned by aifc.open() when a file is opened for
writing have all the above methods, except for readframes and
setpos. In addition the following methods exist. The
get methods can only be called after the corresponding
set methods have been called. Before the first
writeframes() or writeframesraw(), all parameters except
for the number of frames must be filled in.
---
node196.html
node192.html
node194.html
node1.html
node270.html
guido@python.org


13.4 Built-in Module jpeg

node197.html
node192.html
node195.html
node1.html
node270.html
---
# 13.4 Built-in Module jpeg
The module jpeg provides access to the jpeg compressor and
decompressor written by the Independent JPEG Group. JPEG is a (draft?)\
standard for compressing pictures. For details on jpeg or the
Independent JPEG Group software refer to the JPEG standard or the
documentation provided with the software.
The jpeg module defines these functions:
Compress and uncompress raise the error jpeg.error in case of errors.
---
guido@python.org


13.5 Built-in Module rgbimg

node198.html
node192.html
node196.html
node1.html
node270.html
---
# 13.5 Built-in Module rgbimg
The rgbimg module allows python programs to access SGI imglib image
files (also known as `.rgb' files). The module is far from
complete, but is provided anyway since the functionality that there is
is enough in some cases. Currently, colormap files are not supported.
The module defines the following variables and functions:
---
guido@python.org


13.6 Standard Module imghdr

node199.html
node192.html
node197.html
node1.html
node270.html
---
# 13.6 Standard Module imghdr
The imghdr module determines the type of image contained in a
file or byte stream.
The imghdr module defines the following function:
The following image types are recognized, as listed below with the
return value from what:
You can extend the list of file types imghdr can recognize by
appending to this variable:
Example:
```text
>>> import imghdr
>>> imghdr.what('/tmp/bass.gif')
'gif'
```
---
guido@python.org


14 Cryptographic Services

node200.html
lib.html
node198.html
node1.html
node270.html
---
# 14 Cryptographic Services
The modules described in this chapter implement various algorithms of
a cryptographic nature. They are available at the discretion of the
installation. Here's an overview:
Hardcore cypherpunks will probably find the cryptographic modules
written by Andrew Kuchling of further interest; the package adds
built-in modules for DES and IDEA encryption, provides a Python module
for reading and decrypting PGP files, and then some. These modules
are not distributed with Python but available separately. See the URL
http://www.magnet.com/ãmk/python/pct.html or send email to
amk@magnet.com for more information.
---
- 14.1 Built-in Module md5 (node200.html#SECTION0015100000000000000000)
14.2 Built-in Module mpz (node201.html#SECTION0015200000000000000000)
14.3 Built-in Module rotor (node202.html#SECTION0015300000000000000000)
---
guido@python.org


1 Introduction

node3.html
lib.html
node1.html
node1.html
node270.html
---
# 1 Introduction
The ``Python library'' contains several different kinds of components.
It contains data types that would normally be considered part of the
``core'' of a language, such as numbers and lists. For these types,
the Python language core defines the form of literals and places some
constraints on their semantics, but does not fully define the
semantics. (On the other hand, the language core does define
syntactic properties like the spelling and priorities of operators.)
The library also contains built-in functions and exceptions --
objects that can be used by all Python code without the need of an
import statement. Some of these are defined by the core
language, but many are not essential for the core semantics and are
only described here.
The bulk of the library, however, consists of a collection of modules.
There are many ways to dissect this collection. Some modules are
written in C and built in to the Python interpreter; others are
written in Python and imported in source form. Some modules provide
interfaces that are highly specific to Python, like printing a stack
trace; some provide interfaces that are specific to particular
operating systems, like socket I/O; others provide interfaces that are
specific to a particular application domain, like the World-Wide Web.
Some modules are avaiable in all versions and ports of Python; others
are only available when the underlying system supports or requires
them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed.
This manual is organized ``from the inside out'': it first describes
the built-in data types, then the built-in functions and exceptions,
and finally the modules, grouped in chapters of related modules. The
ordering of the chapters as well as the ordering of the modules within
each chapter is roughly from most relevant to least important.
This means that if you start reading this manual from the start, and
skip to the next chapter when you get bored, you will get a reasonable
overview of the available modules and application areas that are
supported by the Python library. Of course, you don't have to
read it like a novel -- you can also browse the table of contents (in
front of the manual), or look for a specific function, module or term
in the index (in the back). And finally, if you enjoy learning about
random subjects, you choose a random page number (see module
rand) and read a section or two.
Let the show begin!
---
node3.html
lib.html
node1.html
node1.html
node270.html
guido@python.org


Type Objects

node21.html
node14.html
node19.html
node1.html
node270.html
---
### Type Objects
Type objects represent the various object types. An object's type is
accessed by the built-in function type(). There are no special
operations on types. The standard module types defines names
for all standard built-in types.
Types are written like this: <type 'int'>.
---
guido@python.org


14.1 Built-in Module md5

node201.html
node199.html
node199.html
node1.html
node270.html
---
# 14.1 Built-in Module md5
This module implements the interface to RSA's MD5 message digest
algorithm (see also Internet RFC 1321). Its use is quite
straightforward: use the md5.new() to create an md5 object.
You can now feed this object with arbitrary strings using the
update() method, and at any point you can ask it for the
digest (a strong kind of 128-bit checksum,
a.k.a. ``fingerprint'') of the contatenation of the strings fed to it
so far using the digest() method.
For example, to obtain the digest of the string "Nobody inspects
the spammish repetition":
```text
>>> import md5
>>> m = md5.new()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
```
More condensed:
```text
>>> md5.new("Nobody inspects the spammish repetition").digest()
'\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351'
```
An md5 object has the following methods:
---
guido@python.org


14.2 Built-in Module mpz

node202.html
node199.html
node200.html
node1.html
node270.html
---
# 14.2 Built-in Module mpz
This is an optional module. It is only available when Python is
configured to include it, which requires that the GNU MP software is
installed.
This module implements the interface to part of the GNU MP library,
which defines arbitrary precision integer and rational number
arithmetic routines. Only the interfaces to the integer
(`mpz_...') routines are provided. If not stated
otherwise, the description in the GNU MP documentation can be applied.
In general, mpz-numbers can be used just like other standard
Python numbers, e.g. you can use the built-in operators like +,
*, etc., as well as the standard built-in functions like
abs, int, ..., divmod, pow.
Please note: the bitwise-xor operation has been implemented as
a bunch of ands, inverts and ors, because the library
lacks an mpz_xor function, and I didn't need one.
You create an mpz-number by calling the function called mpz (see
below for an exact description). An mpz-number is printed like this:
mpz(value).
A number of extra functions are defined in this module. Non
mpz-arguments are converted to mpz-values first, and the functions
return mpz-numbers.
An mpz-number has one method:
---
node202.html
node199.html
node200.html
node1.html
node270.html
guido@python.org


14.3 Built-in Module rotor

node203.html
node199.html
node201.html
node1.html
node270.html
---
# 14.3 Built-in Module rotor
This module implements a rotor-based encryption algorithm, contributed by
Lance Ellinghouse. The design is derived from the Enigma device, a machine
used during World War II to encipher messages. A rotor is simply a
permutation. For example, if the character `A' is the origin of the rotor,
then a given rotor might map `A' to `L', `B' to `Z', `C' to `G', and so on.
To encrypt, we choose several different rotors, and set the origins of the
rotors to known positions; their initial position is the ciphering key. To
encipher a character, we permute the original character by the first rotor,
and then apply the second rotor's permutation to the result. We continue
until we've applied all the rotors; the resulting character is our
ciphertext. We then change the origin of the final rotor by one position,
from `A' to `B'; if the final rotor has made a complete revolution, then we
rotate the next-to-last rotor by one position, and apply the same procedure
recursively. In other words, after enciphering one character, we advance
the rotors in the same fashion as a car's odometer. Decoding works in the
same way, except we reverse the permutations and apply them in the opposite
order.
The available functions in this module are:
Rotor objects have the following methods:
An example usage:
```text
>>> import rotor
>>> rt = rotor.newrotor('key', 12)
>>> rt.encrypt('bar')
'\2534\363'
>>> rt.encryptmore('bar')
'\357\375$'
>>> rt.encrypt('bar')
'\2534\363'
>>> rt.decrypt('\2534\363')
'bar'
>>> rt.decryptmore('\357\375$')
'bar'
>>> rt.decrypt('\357\375$')
'l(\315'
>>> del rt
```
The module's code is not an exact simulation of the original Enigma device;
it implements the rotor encryption scheme differently from the original. The
most important difference is that in the original Enigma, there were only 5
or 6 different rotors in existence, and they were applied twice to each
character; the cipher key was the order in which they were placed in the
machine. The Python rotor module uses the supplied key to initialize a
random number generator; the rotor permutations and their initial positions
are then randomly generated. The original device only enciphered the
letters of the alphabet, while this module can handle any 8-bit binary data;
it also produces binary output. This module can also operate with an
arbitrary number of rotors.
The original Enigma cipher was broken in 1944. The version implemented here is probably a good deal more difficult to crack
(especially if you use many rotors), but it won't be impossible for
a truly skilful and determined attacker to break the cipher. So if you want
to keep the NSA out of your files, this rotor cipher may well be unsafe, but
for discouraging casual snooping through your files, it will probably be
just fine, and may be somewhat safer than using the Unix crypt
command.
---
node203.html
node199.html
node201.html
node1.html
node270.html
guido@python.org


15 Macintosh Specific Services

node204.html
lib.html
node202.html
node1.html
node270.html
---
# 15 Macintosh Specific Services
The modules in this chapter are available on the Apple Macintosh only.
Aside from the modules described here there are also interfaces to
various MacOS toolboxes, which are currently not extensively
described. The toolboxes for which modules exist are:
AE (Apple Events),
Cm (Component Manager),
Ctl (Control Manager),
Dlg (Dialog Manager),
Evt (Event Manager),
Fm (Font Manager),
List (List Manager),
Menu (Moenu Manager),
Qd (QuickDraw),
Qt (QuickTime),
Res (Resource Manager and Handles),
Scrap (Scrap Manager),
Snd (Sound Manager),
TE (TextEdit),
Waste (non-Apple TextEdit replacement) and
Win (Window Manager).
If applicable the module will define a number of Python objects for
the various structures declared by the toolbox, and operations will be
implemented as methods of the object. Other operations will be
implemented as functions in the module. Not all operations possible in
C will also be possible in Python (callbacks are often a problem), and
parameters will occasionally be different in Python (input and output
buffers, especially). All methods and functions have a __doc__
string describing their arguments and return values, and for
additional description you are referred to Inside Mac or similar
works.
---
- 15.1 Built-in Module mac (node204.html#SECTION0016100000000000000000)
15.2 Standard Module macpath (node205.html#SECTION0016200000000000000000)
15.3 Built-in Module ctb (node206.html#SECTION0016300000000000000000)
- connection object (node207.html#SECTION0016310000000000000000)
15.4 Built-in Module macconsole (node208.html#SECTION0016400000000000000000)
- macconsole options object (node209.html#SECTION0016410000000000000000)
console window object (node210.html#SECTION0016420000000000000000)
15.5 Built-in Module macdnr (node211.html#SECTION0016500000000000000000)
- dnr result object (node212.html#SECTION0016510000000000000000)
15.6 Built-in Module macfs (node213.html#SECTION0016600000000000000000)
- FSSpec objects (node214.html#SECTION0016610000000000000000)
alias objects (node215.html#SECTION0016620000000000000000)
FInfo objects (node216.html#SECTION0016630000000000000000)
15.7 Standard Module ic (node217.html#SECTION0016700000000000000000)
- IC objects (node218.html#SECTION0016710000000000000000)
15.8 Built-in Module MacOS (node219.html#SECTION0016800000000000000000)
15.9 Standard Module macostools (node220.html#SECTION0016900000000000000000)
15.10 Standard Module findertools (node221.html#SECTION00161000000000000000000)
15.11 Built-in Module mactcp (node222.html#SECTION00161100000000000000000)
- TCP Stream Objects (node223.html#SECTION00161110000000000000000)
TCP Status Objects (node224.html#SECTION00161120000000000000000)
UDP Stream Objects (node225.html#SECTION00161130000000000000000)
15.12 Built-in Module macspeech (node226.html#SECTION00161200000000000000000)
- voice objects (node227.html#SECTION00161210000000000000000)
speech channel objects (node228.html#SECTION00161220000000000000000)
15.13 Standard Module EasyDialogs (node229.html#SECTION00161300000000000000000)
15.14 Standard Module FrameWork (node230.html#SECTION00161400000000000000000)
- Application objects (node231.html#SECTION00161410000000000000000)
Window Objects (node232.html#SECTION00161420000000000000000)
ControlsWindow Object (node233.html#SECTION00161430000000000000000)
ScrolledWindow Object (node234.html#SECTION00161440000000000000000)
DialogWindow Objects (node235.html#SECTION00161450000000000000000)
15.15 Standard Module MiniAEFrame (node236.html#SECTION00161500000000000000000)
- AEServer Objects (node237.html#SECTION00161510000000000000000)
---
guido@python.org


15.1 Built-in Module mac

node205.html
node203.html
node203.html
node1.html
node270.html
---
# 15.1 Built-in Module mac
This module provides a subset of the operating system dependent
functionality provided by the optional built-in module posix.
It is best accessed through the more portable standard module
os.
The following functions are available in this module:
chdir,
close,
dup,
fdopen,
getcwd,
lseek,
listdir,
mkdir,
open,
read,
rename,
rmdir,
stat,
sync,
unlink,
write,
as well as the exception error. Note that the times returned by
stat() are floating-point values, like all time values in
MacPython.
One additional function is available: xstat(). This function
returns the same information as stat(), but with three extra
values appended: the size of the resource fork of the file and its
4-char creator and type.
---
guido@python.org


15.2 Standard Module macpath

node206.html
node203.html
node204.html
node1.html
node270.html
---
# 15.2 Standard Module macpath
This module provides a subset of the pathname manipulation functions
available from the optional standard module posixpath. It is
best accessed through the more portable standard module os, as
os.path.
The following functions are available in this module:
normcase,
normpath,
isabs,
join,
split,
isdir,
isfile,
walk,
exists.
For other functions available in posixpath dummy counterparts
are available.
---
guido@python.org


15.3 Built-in Module ctb

node207.html
node203.html
node205.html
node1.html
node270.html
---
# 15.3 Built-in Module ctb
This module provides a partial interface to the Macintosh
Communications Toolbox. Currently, only Connection Manager tools are
supported. It may not be available in all Mac Python versions.
---
- connection object (node207.html#SECTION0016310000000000000000)
---
guido@python.org


connection object

node208.html
node206.html
node206.html
node1.html
node270.html
---
## connection object
For all connection methods that take a timeout argument, a value
of -1 is indefinite, meaning that the command runs to completion.
---
node208.html
node206.html
node206.html
node1.html
node270.html
guido@python.org


15.4 Built-in Module macconsole

node209.html
node203.html
node207.html
node1.html
node270.html
---
# 15.4 Built-in Module macconsole
This module is available on the Macintosh, provided Python has been
built using the Think C compiler. It provides an interface to the
Think console package, with which basic text windows can be created.
---
- macconsole options object (node209.html#SECTION0016410000000000000000)
console window object (node210.html#SECTION0016420000000000000000)
---
guido@python.org


macconsole options object

node210.html
node208.html
node208.html
node1.html
node270.html
---
## macconsole options object
These options are examined when a window is created:
---
guido@python.org


The Null Object

node22.html
node14.html
node20.html
node1.html
node270.html
---
### The Null Object
This object is returned by functions that don't explicitly return a
value. It supports no special operations. There is exactly one null
object, named None (a built-in name).
It is written as None.
---
guido@python.org


console window object

node211.html
node208.html
node209.html
node1.html
node270.html
---
## console window object
---
guido@python.org


15.5 Built-in Module macdnr

node212.html
node203.html
node210.html
node1.html
node270.html
---
# 15.5 Built-in Module macdnr
This module provides an interface to the Macintosh Domain Name
Resolver. It is usually used in conjunction with the mactcp
module, to map hostnames to IP-addresses. It may not be available in
all Mac Python versions.
The macdnr module defines the following functions:
---
- dnr result object (node212.html#SECTION0016510000000000000000)
---
guido@python.org


dnr result object

node213.html
node211.html
node211.html
node1.html
node270.html
---
## dnr result object
Since the DNR calls all execute asynchronously you do not get the
results back immediately. Instead, you get a dnr result object. You
can check this object to see whether the query is complete, and access
its attributes to obtain the information when it is.
Alternatively, you can also reference the result attributes directly,
this will result in an implicit wait for the query to complete.
The rtnCode and cname attributes are always available, the
others depend on the type of query (address, hinfo or mx).
The simplest way to use the module to convert names to dotted-decimal
strings, without worrying about idle time, etc:
```text
>>> def gethostname(name):
... import macdnr
... dnrr = macdnr.StrToAddr(name)
... return macdnr.AddrToStr(dnrr.ip0)
```
---
guido@python.org


15.6 Built-in Module macfs

node214.html
node203.html
node212.html
node1.html
node270.html
---
# 15.6 Built-in Module macfs
This module provides access to macintosh FSSpec handling, the Alias
Manager, finder aliases and the Standard File package.
Whenever a function or method expects a file argument, this
argument can be one of three things: (1) a full or partial Macintosh
pathname, (2) an FSSpec object or (3) a 3-tuple (wdRefNum,
parID, name) as described in Inside Mac VI. A description of aliases
and the standard file package can also be found there.
---
- FSSpec objects (node214.html#SECTION0016610000000000000000)
alias objects (node215.html#SECTION0016620000000000000000)
FInfo objects (node216.html#SECTION0016630000000000000000)
---
node214.html
node203.html
node212.html
node1.html
node270.html
guido@python.org


FSSpec objects

node215.html
node213.html
node213.html
node1.html
node270.html
---
## FSSpec objects
---
guido@python.org


alias objects

node216.html
node213.html
node214.html
node1.html
node270.html
---
## alias objects
Note that it is currently not possible to directly manipulate a resource
as an alias object. Hence, after calling Update or after
Resolve indicates that the alias has changed the Python program
is responsible for getting the data from the alias object and
modifying the resource.
---
guido@python.org


FInfo objects

node217.html
node213.html
node215.html
node1.html
node270.html
---
## FInfo objects
See Inside Mac for a complete description of what the various fields
mean.
---
guido@python.org


15.7 Standard Module ic

node218.html
node203.html
node216.html
node1.html
node270.html
---
# 15.7 Standard Module ic
This module provides access to macintosh Internet Config package,
which stores preferences for Internet programs such as mail address,
default homepage, etc. Also, Internet Config contains an elaborate set
of mappings from Macintosh creator/type codes to foreign filename
extensions plus information on how to transfer files (binary, ascii,
etc).
There is a low-level companion module icglue which provides the
basic ic access functionality. This low-level module is not
documented, but the docstrings of the routines document the parameters
and the routine names are the same as for the Pascal or C API to
Internet Config, so the standard IC programmers documentation can be
used if this module is needed.
The ic module defines the error exception and symbolic
names for all error codes IC can produce, see the source for details.
The ic module defines the following functions:
---
- IC objects (node218.html#SECTION0016710000000000000000)
---
guido@python.org


IC objects

node219.html
node217.html
node217.html
node1.html
node270.html
---
## IC objects
IC objects have a mapping interface, hence to obtain the mail address
you simply get ic['MailAddress']. Assignment also works, and
changes the option in the configuration file.
The module knows about various datatypes, and converts the internal IC
representation to a ``logical'' python datastructure. Running the
ic module standalone will run a test program that lists all
keys and values in your IC database, this will have to server as
documentation.
If the module does not know how to represent the data it returns an
instance of the ICOpaqueData type, with the raw data in its
data attribute. Objects of this type are also acceptable values
for assignment.
Besides the dictionary interface IC objects have the following methods:
---
node219.html
node217.html
node217.html
node1.html
node270.html
guido@python.org


15.8 Built-in Module MacOS

node220.html
node203.html
node218.html
node1.html
node270.html
---
# 15.8 Built-in Module MacOS
This module provides access to MacOS specific functionality in the
python interpreter, such as how the interpreter eventloop functions
and the like. Use with care.
Note the capitalisation of the module name, this is a historical
artefact.
---
node220.html
node203.html
node218.html
node1.html
node270.html
guido@python.org


File Objects

node23.html
node14.html
node21.html
node1.html
node270.html
---
### File Objects
File objects are implemented using C's stdio package and can be
created with the built-in function open() described under
Built-in Functions below. They are also returned by some other
built-in functions and methods, e.g. posix.popen() and
posix.fdopen() and the makefile() method of socket
objects.
When a file operation fails for an I/O-related reason, the exception
IOError is raised. This includes situations where the
operation is not defined for some reason, like seek() on a tty
device or writing a file opened for reading.
Files have the following methods:
File objects also offer the following attributes:
---
node23.html
node14.html
node21.html
node1.html
node270.html
guido@python.org


15.9 Standard Module macostools

node221.html
node203.html
node219.html
node1.html
node270.html
---
# 15.9 Standard Module macostools
This module contains some convenience routines for file-manipulation
on the Macintosh.
The macostools module defines the following functions:
Note that the process of creating finder aliases is not specified in
the Apple documentation. Hence, aliases created with mkalias
could conceivably have incompatible behaviour in some cases.
---
guido@python.org


15.10 Standard Module findertools

node222.html
node203.html
node220.html
node1.html
node270.html
---
# 15.10 Standard Module findertools
This module contains routines that give Python programs access to some
functionality provided by the finder. They are implemented as wrappers
around the AppleEvent interface to the finder.
All file and folder parameters can be specified either as full
pathnames or as FSSpec objects.
The findertools module defines the following functions:
---
guido@python.org


15.11 Built-in Module mactcp

node223.html
node203.html
node221.html
node1.html
node270.html
---
# 15.11 Built-in Module mactcp
This module provides an interface to the Macintosh TCP/IP driver
MacTCP. There is an accompanying module macdnr which provides an
interface to the name-server (allowing you to translate hostnames to
ip-addresses), a module MACTCPconst which has symbolic names for
constants constants used by MacTCP. Since the builtin module
socket is also available on the mac it is usually easier to use
sockets in stead of the mac-specific MacTCP API.
A complete description of the MacTCP interface can be found in the
Apple MacTCP API documentation.
---
- TCP Stream Objects (node223.html#SECTION00161110000000000000000)
TCP Status Objects (node224.html#SECTION00161120000000000000000)
UDP Stream Objects (node225.html#SECTION00161130000000000000000)
---
guido@python.org


TCP Stream Objects

node224.html
node222.html
node222.html
node1.html
node270.html
---
## TCP Stream Objects
---
node224.html
node222.html
node222.html
node1.html
node270.html
guido@python.org


TCP Status Objects

node225.html
node222.html
node223.html
node1.html
node270.html
---
## TCP Status Objects
This object has no methods, only some members holding information on
the connection. A complete description of all fields in this objects
can be found in the Apple documentation. The most interesting ones are:
---
guido@python.org


UDP Stream Objects

node226.html
node222.html
node224.html
node1.html
node270.html
---
## UDP Stream Objects
Note that, unlike the name suggests, there is nothing stream-like
about UDP.
---
guido@python.org


15.12 Built-in Module macspeech

node227.html
node203.html
node225.html
node1.html
node270.html
---
# 15.12 Built-in Module macspeech
This module provides an interface to the Macintosh Speech Manager,
allowing you to let the Macintosh utter phrases. You need a version of
the speech manager extension (version 1 and 2 have been tested) in
your Extensions folder for this to work. The module does not
provide full access to all features of the Speech Manager yet. It may
not be available in all Mac Python versions.
---
- voice objects (node227.html#SECTION00161210000000000000000)
speech channel objects (node228.html#SECTION00161220000000000000000)
---
guido@python.org


voice objects

node228.html
node226.html
node226.html
node1.html
node270.html
---
## voice objects
Voice objects contain the description of a voice. It is currently not
yet possible to access the parameters of a voice.
---
guido@python.org


speech channel objects

node229.html
node226.html
node227.html
node1.html
node270.html
---
## speech channel objects
A speech channel object allows you to speak strings with slightly more
control than SpeakString(), and allows you to use multiple
speakers at the same time. Please note that channel pitch and rate are
interrelated in some way, so that to make your Macintosh sing you will
have to adjust both.
---
guido@python.org


15.13 Standard Module EasyDialogs

node230.html
node203.html
node228.html
node1.html
node270.html
---
# 15.13 Standard Module EasyDialogs
The EasyDialogs module contains some simple dialogs for
the Macintosh, modelled after the stdwin dialogs with similar
names. All routines have an optional parameter id with which you
can override the DLOG resource used for the dialog, as long as the
item numbers correspond. See the source for details.
The EasyDialogs module defines the following functions:
Note that EasyDialogs does not currently use the notification
manager. This means that displaying dialogs while the program is in
the background will lead to unexpected results and possibly
crashes. Also, all dialogs are modeless and hence expect to be at the
top of the stacking order. This is true when the dialogs are created,
but windows that pop-up later (like a console window) may also result
in crashes.
---
node230.html
node203.html
node228.html
node1.html
node270.html
guido@python.org


Internal Objects

node24.html
node14.html
node22.html
node1.html
node270.html
---
### Internal Objects
See the Python Reference Manual for this information. It
describes code objects, stack frame objects, traceback objects, and
slice objects.
---
guido@python.org