Linux/Unix > Python Essential Reference, Second Edition > A. The Python Library > Internet Data Handling and Encoding | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105081080061094143037034

### Internet Data Handling and Encoding

The modules in this section are used to encode and decode data formats that are widely used in Internet applications.

#### `base64`

The `base64` module is used to encode and decode data using base64 encoding. base64 is commonly used to encode binary data in mail attachments.

    decode(input, output)

Decodes base64-encoded data. `input` is a filename or a file object open for reading. `output` is a filename or a file object open for writing.

    decodestring(s)

Decodes a base64-encoded string `s` . Returns a string containing the decoded binary data.

    encode(input, output)

Encodes data using base64. `input` is a filename or a file object open for reading. `output` is a filename or a file object open for writing.

    encodestring(s)

Encodes a string `s` using base64.

? See Also binascii (264), Internet RFC 1421.

#### `binascii`

The `binascii` module is used to convert data between binary and a variety of ASCII encodings such as base64, binhex, and uuencode.

    a2b_uu(string)

Converts a line of uuencoded data to binary. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace.

    b2a_uu(data)

Converts a string of binary data to a line of uuencoded ASCII characters. The length of `data` should not be more than 45 bytes.

    a2b_base64(string)

Converts a string of base64-encoded data to binary.

    b2a_base64(data)

Converts a string of binary data to a line of base64-encoded ASCII characters. The length of `data` should not be more than 57 bytes.

    a2b_hex(string)

Converts a string of hex digits to a string of binary data. `string` must contain an even number of digits.

    b2a_hex(data)

Converts a string of binary data to a string of hex digits.

    a2b_hqx(string)

Converts a string of binhex4-encoded data to binary without performing RLE decompression.

    rledecode_hqx(data)

Performs an RLE (Run-Length Encoding) decompression of the binary data in `data`. Returns the decompressed data unless the data input is incomplete, in which case the `Incomplete` exception is raised.

    rlecode_hqx(data)

Performs a binhex4 RLE compression of `data` .

    b2a_hqx(data)

Converts the binary data to a string of binhex4-encoded ASCII characters. `data` should already be RLE coded and have a length divisible by three.

    crc_hqx(data, crc)

Computes the binhex4 CRC checksum of the data. `crc` is a starting value of the checksum.

    crc32(data [, oldcrc])

Computes the CRC-32 checksum of `data` . If supplied, the `oldcrc` parameter allows for incremental calculation of the checksum.

##### Exceptions

    Error

Exception raised on errors.

    Incomplete

Exception raised on incomplete data. This exception occurs when multiple bytes of data are expected, but the input data has been truncated.

? See Also base64 (263), binhex (265), uu (277).

#### `binhex`

The `binhex` module is used to encode and decode files in binhex4, a format commonly used to represent files on the Macintosh.

    binhex(input, output)

Converts a binary file with name `input` to a binhex file. `output` is a filename or an open file-like object supporting `write()` and `close()` methods.

    hexbin(input [, output])

Decodes a binhex file. `input` is either a filename or a file-like object with `read()` and `close()` methods. `output` is the name of the output file. If omitted, the output name is taken from the binhex file.

##### Notes

- Both the data and resource forks are handled on the Macintosh.

- Only the data fork is handled on other platforms.

? See Also binascii (264), macostools (176).

#### `mailcap`

The `mailcap` module is used to read UNIX mailcap files. Mailcap files are used to tell mail readers and Web browsers how to process files with different MIME types. The contents of a mailcap file typically look something like this:

    video/mpeg; xmpeg %s
    application/pdf; acroread %s

When data of a given MIME type is encountered, the mailcap file is consulted to find an application for handling that data.

    getcaps()

Reads all available mailcap files and returns a dictionary mapping MIME types to a mailcap entry. Mailcap files are read from `$HOME/.mailcap`, `/etc/mailcap`, `/usr/etc/mailcap`, and `/usr/local/etc/mailcap`.

    findmatch(caps, mimetype [, key [, filename [, plist]]])

Searches the dictionary `caps` for a mailcap entry matching `mimetype` . `key` is a string indicating an action and is typically `'view'`, `'compose'`, or `'edit'`. `filename` is the name of the file that’s substituted for the `%s` keyword in the mailcap entry. `plist` is a list of named parameters and is described further in the online documentation at http://www.python.org/doc/lib/module-mailcap.html. Returns a tuple (`cmd` `,` `mailcap` ) containing the command from the mailcap file and the raw mailcap entry.

##### Example

    import mailcap
    import urllib
    import os
    # Go fetch a document
    urllib.urlretrieve("http://www.swig.org/Doc1.1/PDF/Python.pdf", "/tmp/tmp1234")

    caps = mailcap.getgaps()
    cmd, mc = mailcap.findmatch(caps,'application/pdf',filename='/tmp/tmp1234')
    if cmd:
        os.system(cmd + " &")
    else:
        print "No application for type application/pdf"

? See Also http://www.python.org/doc/lib/module-mailcap.html, mimetypes (268), Internet RFC 1524.

#### `mimetools`

The `mimetools` module provides a number of functions for manipulating MIME-encoded messages. MIME (Multipurpose Internet Mail Extensions) is a standard for sending multipart multimedia data through Internet mail. Parts of the standard are also used in other settings, such as the HTTP protocol. A MIME-encoded message looks similar to this:

    Content-Type: multipart/mixed; boundary="====_931526447=="
    Date: Fri, 06 Jul 2001 03:20:47 -0500
    From: John Doe <johndoe@foo.com>
    To: Jane Doe (janedoe@foo.com>
    Subject: Important Message From John Doe

    --====_931526447==
    Content-Type: text/plain; charset="us-ascii"

    Here is that document you asked for ... don't show anyone else ;-)

    --====_931526447==
    Content-Type: application/msword; name="list.doc"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment; filename="list.doc"

    SXQgd2FzIGEgbG9uZyBob3QgZGF5IGluIHRoZSBtb250aCBvZiBKdWx5LCB3aGVuIExhcnJ5IHN0
    YXJ0ZWQgdGFsa2luZwphYm91dCBzb2Npby1wb2xpdGljYWwgc2NhbGFibGUgaW1tZXJzaXZlIHZp
    cnR1YWwgdGVtcG9yYWwKY29sbGFib3JhdGl2ZSBwYXJhbGxlbCBoaWdoIHBlcmZvcm1hbmNlIHdl
    Yi1iYXNlZCBtb2JpbGUKb2JqZWN0LW9yaWVudGVkIHNjaWVudGlmaWMgY29tcHV0aW5nIGVudmly
    b25tZW50cy4gIEZvcnR1bmF0ZWx5LCBQZXRlCmhhZCByZW1lbWJlcmVkIHRvIGJyaW5nIGhpcyAu
    NDUuLi4KCg==

    --====_931526447==--

MIME messages are broken into parts delimited by a line separator such as `--====_931526447==` above. This separator always starts with a double hyphen as shown. The final separator has a trailing double hyphen (`-`) appended to indicate the end of the message. Immediately following each separator is a set of RFC 822 headers describing the content-type and encoding. Data is separated from the headers by a single blank line.

The `mimetools` module defines the following functions to parse headers and decode data:

    Message(file [, seekable])

Parses MIME headers and returns a `Message` object derived from the `rfc822.Message` class. `file` and `seekable` have the same meaning as for `rfc822.Message`.

    choose_boundary()

Creates a unique string of the form `'``hostipaddr.uid.pid.timestamp.random` `'` that can be used as a part boundary when generating a message.

    decode(input, output, encoding)

Reads encoded data from the open file object `input` and writes the decoded data to the open file object `output` . `encoding` specifies the encoding method: `'base64'`, `'quoted-printable'`, or `'uuencode'`.

    encode(input, output, encoding)

Reads data from the open file object `input` , encodes it, and writes it to the open file object `output` . Encoding types are the same as for `decode()`.

    copyliteral(input, output)

Read lines of text from the open file `input` until EOF and writes them to the open file `output` .

    copybinary(input, output)

Read blocks of binary data from the open file `input` until EOF and writes them to the open file `output` .

Instances of the `Message` class support all the methods described in the `rfc822` module. In addition, the following methods are available:

    m.getplist()

Returns the parameters for the content-type header as a list of strings. If the message contains the header `'Content-type: text/html; charset=US-ASCII'`, for example, this function returns `['charset=US-ASCII']`. For parameters of the form `'``key=value` `'`, `key` is converted to lowercase, while `value` is unchanged.

    m.getparam(name)

Returns the value of the first parameter of the form `'``name=value` `'` from the `'content-type'` header. If `value` is surrounded by quotes of the form `'<...>'` or `"..."`, they’re removed.

    m.getencoding()

Returns the encoding specified in the `'content-transfer-encoding'` message header. If no such header exists, returns `'7bit'`.

    m.gettype()

Returns the message type from the `'content-type'` header. Types are returned as a string of the form `'``type/subtype` `'`. If no content-type header is available, `'text/plain'` is returned.

    m.getmaintype()

Returns the primary type from the `'content-type'` header. If no such header exists, returns `'text'`.

    m.getsubtype()

Returns the subtype from the `'content-type'` header. If no such header exists, returns `'plain'`.

? See Also rfc822 (274), mimetypes (268), MimeWriter (271), multifile (272), mailcap (265), Internet RFC 1521.

#### `mimetypes`

The `mimetypes` module is used to guess the MIME type associated with a file, based on its filename extension. It also converts MIME types to their standard filename extensions. MIME types consist of a type/subtype pair. The following table shows the MIME types currently recognized by this module:

File Suffix | MIME Type
--- | ---
`.a` | application/octet-stream
`.ai` | application/postscript
`.aif` | audio/x-aiff
`.aifc` | audio/x-aiff
`.aiff` | audio/x-aiff
`.au` | audio/basic
`.avi` | video/x-msvideo
`.bcpio` | application/x-bcpio
`.bin` | application/octet-stream
`.cdf` | application/x-netcdf
`.cpio` | application/x-cpio
`.csh` | application/x-csh
`.dll` | application/octet-stream
`.dvi` | application/x-dvi
`.exe` | application/octet-stream
`.eps` | application/postscript
`.etx` | text/x-setext
`.gif` | image/gif
`.gtar` | application/x-gtar
`.hdf` | application/x-hdf
`.htm` | text/html
`.html` | text/html
`.ief` | image/ief
`.jpe` | image/jpeg
`.jpeg` | image/jpeg
`.jpg` | image/jpeg
`.latex` | application/x-latex
`.man` | application/x-troff-man
`.me` | application/x-troff-me
`.mif` | application/x-mif
`.mov` | video/quicktime
`.movie` | video/x-sgi-movie
`.mpe` | video/mpeg
`.mpeg` | video/mpeg
`.mpg` | video/mpeg
`.ms` | application/x-troff-ms
`.nc` | application/x-netcdf
`.o` | application/octet-stream
`.obj` | application/octet-stream
`.oda` | application/oda
`.pbm` | image/x-portable-bitmap
`.pdf` | application/pdf
`.pgm` | image/x-portable-graymap
`.pnm` | image/x-portable-anymap
`.png` | image/png
`.ppm` | image/x-portable-pixmap
`.py` | text/x-python
`.pyc` | application/x-python-code
`.ps` | application/postscript
`.qt` | video/quicktime
`.ras` | image/x-cmu-raster
`.rgb` | image/x-rgb
`.rdf` | application/xml
`.roff` | application/x-troff
`.rtf` | application/rtf
`.rtx` | text/richtext
`.sgm` | text/x-sgml
`.sgml` | text/x-sgml
`.sh` | application/x-sh
`.shar` | application/x-shar
`.snd` | audio/basic
`.so` | application/octet-stream
`.src` | application/x-wais-source
`.sv4cpio` | application/x-sv4cpio
`.sv4crc` | application/x-sv4crc
`.t` | application/x-troff
`.tar` | application/x-tar
`.tcl` | application/x-tcl
`.tex` | application/x-tex
`.texi` | application/x-texinfo
`.texinfo` | application/x-texinfo
`.tif` | image/tiff
`.tiff` | image/tiff
`.tr` | application/x-troff
`.tsv` | text/tab-separated-values
`.txt` | text/plain
`.ustar` | application/x-ustar
`.wav` | audio/x-wav
`.xbm` | image/x-xbitmap
`.xml` | text/xml
`.xsl` | application/xml
`.xpm` | image/x-xpixmap
`.xwd` | image/x-xwindowdump
`.zip` | application/zip

    guess_type(filename)

Guesses the MIME type of a file based on its filename or URL. Returns a tuple (`type` `,` `encoding` ) in which `type` is a string of the form type/subtype and `encoding` is the program used to encode the data (for example, `compress` or `gzip`). Returns (`None` `,` `None` ) if the type cannot be guessed.

    guess_extension(type)

Guesses the standard file extension for a file based on its MIME type. Returns a string with the filename extension including the leading dot (`.`). Returns `None` for unknown types.

    init([files])

Initializes the module. `files` is a sequence of filenames that are read to extract type information. These files contain lines that map a MIME type to a list of acceptable file suffixes such as the following:

    image/jpeg:   jpe jpeg jpg
    text/html:    htm html
    ...

    read_mime_types(filename)

Loads type mapping from a given filename. Returns a dictionary mapping filename extensions to MIME type strings. Returns `None` if `filename` doesn’t exist or cannot be read.

    knownfiles

List of common names for `mime.types` files.

    suffix_map

Dictionary mapping suffixes to suffixes. This is used to allow recognition of encoded files for which the encoding and the type are indicated by the same extension. For example, the `.tgz` extension is mapped to `.tar.gz` to allow the encoding and type to be recognized separately.

    encodings_map

Dictionary mapping filename extensions to encoding types.

    types_map

Dictionary mapping filename extensions to MIME types.

? See Also mimetools (266).

#### `MimeWriter`

The `MimeWriter` module defines the class `MimeWriter` that’s used to generate MIME-encoded multipart files.

    MimeWriter(fp)

Creates a new instance of the `MimeWriter` class. `fp` is an open file object to be used for writing. A `StringIO` object can also be used.

An instance `m` of the `MimeWriter` class has the following methods:

    m.addheader(key, value [, prefix])

Adds a header line of the form `"``key: value` `"` to the MIME message. `prefix` determines where the header is inserted; `0` appends to the end (the default) and `1` inserts at the start.

    m.flushheaders()

Writes all the headers accumulated so far.

    m.startbody(ctype [, plist [, prefix]])

Returns a file-like object that’s used to write to the body of the message. `ctype` specifies the content type and `plist` is a list of tuples of the form (`name` `,` `value` ) containing additional parameters for the content-type declaration. `prefix` has the same meaning as for the `addheader()` method except that its default value is set to insert at the start.

    m.startmultipartbody(subtype [, boundary [, plist [, prefix]]])

Returns a file-like object that’s used to write the body of a multipart message. `subtype` specifies the multipart subtype such as `'mixed'` and `boundary` can be used to provide a user-defined boundary specifier. `plist` is a list containing optional parameters for the subtype, and `prefix` is the same as in the `startbody()` method. Subparts are created using `nextpart()`.

    m.nextpart()

Returns a new instance of `MimeWriter` that represents an individual part in a multipart message. `startmultipartbody()` must be called prior to calling this method.

    m.lastpart()

Used to indicate the last part of a multipart message. Should always be called to terminate a multipart message.

##### Example

The following example takes a list of files passed on the command line and produces a multipart MIME document in which each file is encoded using base64 encoding:

    import sys
    import mimetools, mimetypes, MimeWriter
    # Open the output file and create a MimeWriter
    out = open("output.txt","w")
    writer = MimeWriter.MimeWriter(out)
    # Start a multipart message
    writer.startmultipartbody("mixed")
    writer.flushheaders()
    # Iterate over files passed on the command line
    for file in sys.argv[1:]:
        subpart = writer.nextpart() # Create a new subpart
        # Attempt to guess the file's MIME type and encoding
        type,encoding = mimetypes.guess_type(file)
        if encoding:
                subpart.addheader("Content-encoding",encoding)
                subpart.addheader("Content-transfer-encoding", "base64")
        if type:
             pout = subpart.startbody(type, [("name",file)])
        else:
             pout = subpart.startbody("text/plain",[("name",file)])
        infile = open(file,"rb")
        # Encode the raw data using base64
        mimetools.encode(infile,pout,'base64')
        infile.close()

    # Clean up
    writer.lastpart()
    out.close()

? See Also mimetypes (268), mimetools (266), rfc822 (274), multifile (272).

#### `multifile`

The `multifile` module defines an object that can be used to read multipart text files as found in MIME-encoded messages. The `multifile` object works by splitting a file into a series of logical file-like objects that are delimited by a unique boundary string such as the following:

    --216.150.6.70.100.4397.932677969.082.3036
    Part 1
    ...
    --216.150.6.70.100.4397.932677969.082.3036
    Part 2
    ...
    --216.150.6.70.100.4397.932677969.082.3036--

In this case, the boundary string is of the form returned by the `mimetools.choose_boundary()` function. The last boundary string (with a trailing `-`) marks the end of the multipart data.

    MultiFile(fp [, seekable])

Creates a multifile object. `fp` is a file-like object containing input data. The input object’s `readline()` method is used to read data. If the `seekable` option is set, the multifile object allows random access using the `seek()` and `tell()` methods.

A `MultiFile` object `m` supports the following methods:

    m.push(str)

Pushes a boundary string into the reader. When this string is encountered in the input, it signals an end of section or end of message. More than one boundary marker can be pushed to handle nested multipart data. However, encountering any other boundary than the most recently pushed value raises an error.

    m.readline()

Reads a line of text. If the line matches the most recently pushed boundary, `''` is returned to indicate the end of the part. Furthermore, if the boundary corresponds to an end marker, the `m.last` attribute is set to `1`. Raises `Error` if an EOF is encountered before all boundary strings have been popped.

    m.readlines()

Returns all lines remaining in the current part as a list of strings.

    m.read()

Reads all lines remaining in the current part and returns as a single string.

    m.next()

Skips to the next section. Returns true if a next section exists, false if an end marker is encountered.

    m.pop()

Pops a section boundary. This boundary will no longer be interpreted as EOF.

    m.seek(pos [, whence])

Seeks to a new position within the current section. The `pos` and `whence` arguments are interpreted as for a file seek.

    m.tell()

Returns the file position relative to the start of the current section.

Finally, `MultiFile` instances have two public-instance variables:

    m.level

Nesting depth of the current part.

    m.last

True if the last end-of-file was an end-of-message marker.

##### Example

    # Unpack a MIME encoded mail message into parts
    import mimetools, multifile, sys
    def unpack_part(file,partno=0):
        headers = mimetools.Message(file)    # Get headers
        type = headers.getmaintype()         # Get main content type
        if type == 'multipart':              # Multipart?
              boundary = headers.getparam("boundary")
              file.push(boundary)
              file.readlines()
              while not file.last:
                     file.next()
                     partno = partno + 1
                     unpack_part(file,partno)
              file.pop()
              return
        name = headers.getparam("name")      # Get filename
        if not name: name = "part%d" % (partno,)
        encoding = headers.getencoding()
        print "Unpacking '%s'. Encoding = %s" % (name, encoding)
        if encoding == '7bit':
            outfile = open(name,"w")
            mimetools.copyliteral(file,outfile)
        else:
            outfile = open(name,"wb")
            mimetools.decode(file,outfile,encoding)
        outfile.close()
    # Read a filename from options and unpack it
    f = open(sys.argv[1])
    mf = multifile.MultiFile(f,0)
    unpack_part(mf)

##### Note

- The `MultiFile` class defines a number of methods that can be specialized in a subclass. Please refer to the online library reference at http://www.python.org/doc/lib/module-multifile.html.

? See Also mimetools (266), MimeWriter (271), http://www.python.org/doc/lib/module-multifile.html.

#### `quopri`

The `quopri` module performs quoted-printable transport encoding and decoding. This format is used primarily to encode text files.

    decode(input, output)

Decodes. `input` and `output` are file objects.

    encode(input, output, quotetabs)

Encodes. `input` and `output` are file objects. `quotetabs` , if set to true, forces tab characters to be quoted in addition to the normal quoting rules.

? See Also binascii (264), Internet RFC 1521.

#### `rfc822`

The `rfc822` module is used to parse email headers presented in a format defined by the Internet standard RFC 822. Headers of this form are used in a number of contexts, including mail handling and in the HTTP protocol. A collection of RFC 822 headers looks like this:

    Return-Path: <beazley@cs.uchicago.edu>
    Date: Sun, 15 Apr 03:18:21 -0500 (CDT)
    Message-Id: <199907171518.KAA24322@gargoyle.cs.uchicago.edu>
    Reply-To: beazley@cs.uchicago.edu
    References: <15065.6056.897223.775915@empire-builder.cs.uchicago.edu>
            <20010415041130.008D1D1D8@smack.cs.uchicago.edu>
    Mime-Version: 1.0 (generated by tm-edit 7.78)
    Content-Type: text/plain; charset=US-ASCII
    From: David Beazley <beazley@cs.uchicago.edu>
    To: techstaff@cs
    Subject: Modem problem

    I'm having some trouble running MPI over the ultra-scalable modem array on our
    Beowulf cluster. Can someone take a look at it?

Each header line is of the form `'``headername` `:` `values` `'` and may span multiple lines provided that additional lines are indented with whitespace. Header names are not case sensitive, so a field name of `'Content-Type'` is the same as `'content-type'`. A list of headers is terminated by a single blank line.

RFC 822 headers are parsed by creating an instance of the `Message` class.

    Message(file [, seekable])

Reads RFC 822 headers from the file-like object `file` and returns a `Message` object. Headers are read using `file` `.readline()` until a blank line is encountered. `seekable` is a flag that’s set to zero if `file` is unseekable (such as a file created from a socket).

A `Message` object `m` behaves like a dictionary except that its key values are not case sensitive and it doesn’t support certain dictionary operations, including `update()` and `clear()`.

Method | Description
--- | ---
`m` `[``name` `]` | Returns the value for header name.
`m` `[``name` `]=``value` | Adds a header.
`m` `.keys()` | Returns a list of header names.
`m` `.values()` | Returns a list of header values.
`m` `.items()` | Returns a list of header (`name` `,` `value` ) pairs.
`m` `.has_key(``name` `)` | Tests for the existence of a header name.
`m` `.get(``name` `[,` `default` `])` | Gets a header value. Returns `default` if not found.
`len(``m` `)` | Returns the number of headers.
`str(``m` `)` | Converts headers to an RFC 822–formatted string.

In addition, the following methods are available:

    m.getallmatchingheaders(name)

Returns a list of all lines with headers that match `name` , including continuation lines (if any).

    m.getfirstmatchingheader(name)

Returns the list of lines for the first header matching `name` , including any continuation lines. Returns `None` if `name` doesn’t match any headers.

    m.getrawheader(name)

Returns a string containing the raw text after the colon for the first header matching `name` . Returns `None` if no match is found.

    m.getheader(name [, default])

Like `getrawheader(``name` `)`, but strips all leading and trailing whitespace. `default` specifies a default value to return if no matching header is found.

    m.getaddr(name)

Returns a pair (`full_name` `,` `email_address` ) for a header containing an email address. If no header matches `name` , (`None, None`) is returned.

    m.getaddrlist(name)

Parses a header containing a list of email addresses and returns a list of tuples as returned by the `getaddr()` method. If multiple headers match the named header, all are parsed for addresses (for example, multiple `'cc'` headers).

    m.getdate(name)

Parses a header containing a date and returns a 9-tuple compatible with `time.mktime()`. Returns `None` if no match is found or the date cannot be parsed.

    m.getdate_tz(name)

Parses a header containing a date and returns a 10-tuple in which the first nine elements are the same as returned by `getdate()` and the tenth is a number with the offset of the date’s timezone from UTC (Greenwich Mean Time). Returns `None` if no match is found or the date is unparsable.

Finally, messages have two instance attributes:

    m.headers

A list containing the entire set of header lines.

    m.fp

The file-like object passed when the `Message` was created.

In addition to `Message`, the `rfc822` module defines the following utility functions:

    parsedate(date)

Parses an RFC 822–formatted date such as `'Mon, 16 Apr 2001 17:30:08 -0600'` and returns a 9-tuple that’s compatible with the `time.mktime()` function. Returns `None` if `date` cannot be parsed.

    parsedate_tz(date)

Parses a date, but returns a 10-tuple where the first nine elements are the same as returned by `parsedate()` and the tenth item is the offset of the date’s timezone from UTC. Returns `None` if `date` cannot be parsed.

    mktime_tz(tuple)

Turns a 10-tuple as returned by `parsedate_tz()` into a UTC timestamp. If the timezone item is `None`, assumes local time.

    AddressList(addrlist)

Converts a string containing a list of email addresses into an `AddressList` object. The following operations can be performed on `AddressList` objects:

Operation | Description
--- | ---
`len(``a` `)` | Number of addresses in a list
`str(``a` `)` | Converts `a` back into a string of email addresses
`a` `+` `b` | Combines two lists of addresses, removing duplicates
`a` `-` `b` | Removes all addresses in list `b` from list `a`

##### Example

    import rfc822
    # Open a mail message
    f = open("mailmessage")
    # Read the headers
    m = rfc822.Message(f)
    # Extract a few fields
    m_from = m["From"]
    m_to = m.getaddr("To")
    m_subject = m["Subject"]

##### Note

- The `Message` class defines a few additional methods that can be specialized in a subclass. For details, please refer to the online documentation at http://www.python.org/doc/lib/module-rfc822.html.

? See Also mimetools (266), MimeWriter (271), mimetypes (268), mailcap (265), Internet RFC 822, http://www.python.org/doc/lib/module-rfc822.html.

#### `uu`

The `uu` module is used to encode and decode files in uuencode format, commonly used for transferring binary data over an ASCII-only connection.

    encode(input, output [, name [, mode]])

Uuencodes a file. `input` is a file object opened for reading or a filename. `output` is a file object opened for writing or a filename. `name` specifies the name of the file that’s encoded in the uuencoded file. `mode` specifies the mode of the file. By default, `name` and `mode` are taken from the input file.

    decode(input [, output [, mode]])

Decodes a uuencoded file. `input` is a file object opened for reading or a filename. `output` is a file object opened for writing or a filename. `mode` is used to set permission bits and overrides the setting encoded in the input file.

? See Also binascii (264).

#### `xdrlib`

`xdrlib` is used to encode and decode data in the Sun XDR (External Data Representation) format. XDR is often used as a portable way to encode binary data for use in networked applications. It’s used extensively in applications involving remote procedure calls (RPC).

Encoding and decoding is controlled through the use of two classes:

    Packer()

Creates an object for packing data into an XDR representation.

    Unpacker(data)

Creates an object for unpacking XDR-encoded data. `data` is a string containing XDR-encoded data values.

An instance `p` of the `Packer` class supports the following methods:

    p.get_buffer()

Returns the current pack buffer as a string.

    p.reset()

Resets the pack buffer to the empty string.

    p.pack_uint(x)

Packs a 32-bit unsigned integer `x` .

    p.pack_int(x)

Packs a 32-bit signed integer `x` .

    p.pack_enum(x)

Packs an enumeration `x` (an integer).

    p.pack_bool(x)

Packs a Boolean value `x` .

    p.pack_uhyper(x)

Packs a 64-bit unsigned integer `x` .

    p.pack_hyper(x)

Packs a 64-bit signed integer `x` .

    p.pack_float(x)

Packs a single-precision floating-point number.

    p.pack_double(x)

Packs a double-precision floating-point number.

    p.pack_fstring(n, s)

Packs a fixed-length string of length `n` .

    p.pack_fopaque(n, data)

Packs a fixed-length opaque data stream. Similar to `pack_fstring()`.

    p.pack_string(s)

Packs a variable-length string `s` .

    p.pack_opaque(data)

Packs a variable-length opaque data string `data` . Similar to `pack_string()`.

    p.pack_bytes(bytes)

Packs a variable-length byte stream `bytes` . Similar to `pack_string()`.

    p.pack_list(list, pack_func)

Packs a list of homogeneous items. `pack_func` is the function called to pack each data item (for example, `p` `.pack_int`). For each item in the list, an unsigned integer `1` is packed first, followed by the data item. An unsigned integer `0` is packed at the end of the list.

    p.pack_farray(n, array, pack_func)

Packs a fixed-length list of homogeneous items. `n` is the list length, `array` is a list containing the data, and `pack_func` is the function called to pack each data item.

    p.pack_array(list, pack_func)

Packs a variable-length list of homogeneous items by first packing its length and then calling the `pack_farray()` method.

An instance `u` of the `Unpacker` class supports the following methods:

    u.reset(data)

Resets the string buffer with the given data.

    u.get_position()

Returns the current unpack position in the data buffer.

    u.set_position(position)

Sets the data buffer unpack position to `position` .

    u.get_buffer()

Returns the current unpack data buffer as a string.

    u.done()

Indicates unpack completion. Raises an `Error` exception if all the data has not been unpacked.

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.

    u.unpack_int()

Unpacks and returns a 32-bit signed integer.

    u.unpack_uint()

Unpacks and returns a 32-bit unsigned integer. If the unsigned value is larger than `sys.maxint`, it’s returned as an unsigned long integer.

    u.unpack_enum()

Unpacks and returns an enumeration (an integer).

    u.unpack_bool()

Unpacks a Boolean value and returns it as an integer.

    u.unpack_hyper()

Unpacks and returns a 64-bit signed integer as a Python long integer.

    u.unpack_uhyper()

Unpacks and returns a 64-bit unsigned integer as a Python long integer.

    u.unpack_float()

Unpacks and returns a single-precision floating-point number. The value will be converted to double precision when it is returned as a Python floating-point number.

    u.unpack_double()

Unpacks and returns a double-precision floating-point number.

    u.unpack_fstring(n)

Unpacks and returns a fixed-length string. `n` is the number of characters expected.

    u.unpack_fopaque(n)

Unpacks and returns a fixed-length opaque data stream, similarly to `unpack_fstring()`.

    u.unpack_string()

Unpacks and returns a variable-length string.

    u.unpack_opaque()

Unpacks and returns a variable-length opaque data string.

    u.unpack_bytes()

Unpacks and returns a variable-length byte stream.

    u.unpack_list(unpack_func)

Unpacks and returns a list of homogeneous items as packed by `pack_list()`. `unpack_func` is the function called to perform the unpacking for each item (for example, `u` `.unpack_int`).

    u.unpack_farray(n, unpack_func)

Unpacks and returns (as a list) a fixed-length array of homogeneous items. `n` is the number of list elements to expect and `unpack_func` is the function used to unpack each item.

    u.unpack_array(unpack_func)

Unpacks and returns a variable-length list of homogeneous items. `unpack_func` is the function used to unpack each item.

##### Exceptions

    Error

The base exception class. `Error` has a single public data member `msg` containing the description of the error.

    ConversionError

Class derived from `Error`. Contains no additional instance variables.

##### Note

- Objects created with `xdrlib` can be pickled using the `pickle` module.

? See Also struct (144), array (127), Internet RFC 1014.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.