This is Info file /home/pdm/tmp/Python-1.5.2p1/Doc/lib/python-lib.info,
produced by Makeinfo version 1.68 from the input file lib.texi.

   July 6, 1999			1.5.2


File: python-lib.info,  Node: Old classes,  Next: Functions in cgi module,  Prev: Using the cgi module,  Up: cgi

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' stores single value form content as dictionary;
it assumes each field name occurs in the form only once.

   `FormContentDict' stores multiple value form content as a 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.


File: python-lib.info,  Node: Functions in cgi module,  Next: Caring about security,  Prev: Old classes,  Up: cgi

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.

`parse(fp)'
     Parse a query in the environment or from a file (default
     `sys.stdin').

`parse_qs(qs[, keep_blank_values, strict_parsing])'
     Parse a query string given as a string argument (data of type
     `application/x-www-form-urlencoded').  Data are returned as a
     dictionary.  The dictionary keys are the unique query variable
     names and the values are lists of vales for each name.

     The optional argument KEEP_BLANK_VALUES is a flag indicating
     whether blank values in URL encoded queries should be treated as
     blank strings.  A true value indicates that blanks should be
     retained as blank strings.  The default false value indicates that
     blank values are to be ignored and treated as if they were not
     included.

     The optional argument STRICT_PARSING is a flag indicating what to
     do with parsing errors.  If false (the default), errors are
     silently ignored.  If true, errors raise a ValueError exception.

`parse_qsl(qs[, keep_blank_values, strict_parsing])'
     Parse a query string given as a string argument (data of type
     `application/x-www-form-urlencoded').  Data are returned as a list
     of name, value pairs.

     The optional argument KEEP_BLANK_VALUES is a flag indicating
     whether blank values in URL encoded queries should be treated as
     blank strings.  A true value indicates that blanks should be
     retained as blank strings.  The default false value indicates that
     blank values are to be ignored and treated as if they were not
     included.

     The optional argument STRICT_PARSING is a flag indicating what to
     do with parsing errors.  If false (the default), errors are
     silently ignored.  If true, errors raise a ValueError exception.

`parse_multipart(fp, pdict)'
     Parse input of type `multipart/form-data' (for file uploads).
     Arguments are FP for the input file and PDICT for the dictionary
     containing other parameters of `content-type' header

     Returns a dictionary just like `parse_qs()' keys are the field
     names, each value is a list of values for that field.  This is
     easy to use but not much good if you are expecting megabytes to be
     uploaded -- in that case, use the `FieldStorage' class instead
     which is much more flexible.  Note that `content-type' is the raw,
     unparsed contents of the `content-type' header.

     Note that this does not parse nested multipart parts -- use
     `FieldStorage' for that.

`parse_header(string)'
     Parse a header like `content-type' into a main content-type and a
     dictionary of parameters.

`test()'
     Robust test CGI script, usable as main program.  Writes minimal
     HTTP headers and formats all information provided to the script in
     HTML form.

`print_environ()'
     Format the shell environment in HTML.

`print_form(form)'
     Format a form in HTML.

`print_directory()'
     Format the current directory in HTML.

`print_environ_usage()'
     Print a list of useful (used by CGI) environment variables in HTML.

`escape(s[, quote])'
     Convert the characters `&', `<' and `>' in string S to HTML-safe
     sequences.  Use this if you need to display text that might
     contain such characters in HTML.  If the optional flag QUOTE is
     true, the double quote character (`"') is also translated; this
     helps for inclusion in an HTML attribute value, e.g. in `<A
     HREF="...">'.


File: python-lib.info,  Node: Caring about security,  Next: Installing your CGI script on a Unix system,  Prev: Functions in cgi module,  Up: cgi

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.


File: python-lib.info,  Node: Installing your CGI script on a Unix system,  Next: Testing your CGI script,  Prev: Caring about security,  Up: cgi

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 `0755' octal (use `chmod 0755 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:

     #!/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
`0644' for readable and `0666' 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.:

     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).


File: python-lib.info,  Node: Testing your CGI script,  Next: Debugging CGI scripts,  Prev: Installing your CGI script on a Unix system,  Up: cgi

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.


File: python-lib.info,  Node: Debugging CGI scripts,  Next: Common problems and solutions,  Prev: Testing your CGI script,  Up: cgi

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:

     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

     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'
     statement

  2. Assign `sys.stderr' to be `sys.stdout'

  3. Make sure you finish printing the headers and the blank line early

  4. Wrap all remaining code in a `try' ... `except' statement

  5. In the except clause, call `traceback.print_exc()'

   For example:

     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):

     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.


File: python-lib.info,  Node: Common problems and solutions,  Prev: Debugging CGI scripts,  Up: cgi

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.


File: python-lib.info,  Node: urllib,  Next: httplib,  Prev: cgi,  Up: Internet Protocols and Support

Open an arbitrary object given by URL.
======================================

   Open an arbitrary object given by URL (requires sockets).

   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 Universal Resource
Locators (URLs) 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:

`urlopen(url[, data])'
     Open a network object denoted by a URL for reading.  If the URL
     does not have a scheme identifier, or if it has `file:' as its
     scheme identifier, this opens a local file; otherwise it opens a
     socket to a server somewhere on the network.  If the connection
     cannot be made, or if the server returns an error code, the
     `IOError' exception is raised.  If all went well, a file-like
     object is returned.  This supports the following methods:
     `read()', `readline()', `readlines()', `fileno()', `close()',
     `info()' and `geturl()'.

     Except for the `info()' and `geturl()' methods, these methods have
     the same interface as for file objects -- see section *Note File
     Objectsfile:: in this manual.  (It is not a built-in file object,
     however, so it can't be used at those few places where a true
     built-in file object is required.)

     The `info()' method returns an instance of the class
     `mimetools.Message' containing meta-information associated with
     the URL.  When the method is HTTP, these headers are those
     returned by the server at the head of the retrieved HTML page
     (including Content-Length and Content-Type).  When the method is
     FTP, a Content-Length header will be present if (as is now usual)
     the server passed back a file length in response to the FTP
     retrieval request.  When the method is local-file, returned
     headers will include a Date representing the file's last-modified
     time, a Content-Length giving file size, and a Content-Type
     containing a guess at the file's type. See also the description of
     the `mimetools' module.

     The `geturl()' method returns the real URL of the page.  In some
     cases, the HTTP server redirects a client to another URL.  The
     `urlopen()' function handles this transparently, but in some cases
     the caller needs to know which URL the client was redirected to.
     The `geturl()' method can be used to get at this redirected URL.

     If the URL uses the `http:' scheme identifier, the optional DATA
     argument may be given to specify a `POST' request (normally the
     request type is `GET').  The DATA argument must in standard
     `application/x-www-form-urlencoded' format; see the `urlencode()'
     function below.

`urlretrieve(url[, filename[, hook]])'
     Copy a network object denoted by a URL to a local file, if
     necessary.  If the URL points to a local file, or a valid cached
     copy of the object exists, the object is not copied.  Return a
     tuple `(FILENAME, HEADERS)' where FILENAME is the local file name
     under which the object can be found, and HEADERS is either `None'
     (for a local object) or whatever the `info()' method of the object
     returned by `urlopen()' returned (for a remote object, possibly
     cached).  Exceptions are the same as for `urlopen()'.

     The second argument, if present, specifies the file location to
     copy to (if absent, the location will be a tempfile with a
     generated name).  The third argument, if present, is a hook
     function that will be called once on establishment of the network
     connection and once after each block read thereafter.  The hook
     will be passed three arguments; a count of blocks transferred so
     far, a block size in bytes, and the total size of the file.  The
     third argument may be `-1' on older FTP servers which do not
     return a file size in response to a retrieval request.

`urlcleanup()'
     Clear the cache that may have been built up by previous calls to
     `urlretrieve()'.

`quote(string[, safe])'
     Replace special characters in STRING using the `%xx' escape.
     Letters, digits, and the characters `_,.-' are never quoted.  The
     optional SAFE parameter specifies additional characters that
     should not be quoted -- its default value is `'/''.

     Example: `quote('/~connolly/')' yields `'/%7econnolly/''.

`quote_plus(string[, safe])'
     Like `quote()', but also replaces spaces by plus signs, as
     required for quoting HTML form values.  Plus signs in the original
     string are escaped unless they are included in SAFE.

`unquote(string)'
     Replace `%xx' escapes by their single-character equivalent.

     Example: `unquote('/%7Econnolly/')' yields `'/~connolly/''.

`unquote_plus(string)'
     Like `unquote()', but also replaces plus signs by spaces, as
     required for unquoting HTML form values.

`urlencode(dict)'
     Convert a dictionary to a "url-encoded" string, suitable to pass to
     `urlopen()' above as the optional DATA argument.  This is useful
     to pass a dictionary of form fields to a `POST' request.  The
     resulting string is a series of `KEY=VALUE' pairs separated by `&'
     characters, where both KEY and VALUE are quoted using
     `quote_plus()' above.

   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
     Gopherprotocol, 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'.


File: python-lib.info,  Node: httplib,  Next: ftplib,  Prev: urllib,  Up: Internet Protocols and Support

HTTP protocol client
====================

   HTTP protocol client (requires sockets).

   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':

`HTTP([host[, port]])'
     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:

          >>> 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:

       1. 1.  Make exactly one call to the `putrequest()' method.

       2. 2.  Make zero or more calls to the `putheader()' method.

       3. 3.  Call the `endheaders()' method (this can be omitted if
          step 4 makes no calls).

       4. 4.  Optional calls to the `send()' method.

       5. 5.  Call the `getreply()' method.

       6. 6.  Call the `getfile()' method and read the data off the
          file object that it returns.


* Menu:

* HTTP Objects::
* HTTP Example::


File: python-lib.info,  Node: HTTP Objects,  Next: HTTP Example,  Prev: httplib,  Up: httplib

HTTP Objects
------------

   `HTTP' instances have the following methods:

`set_debuglevel(level)'
     Set the debugging level (the amount of debugging output printed).
     The default debug level is `0', meaning no debugging output is
     printed.

`connect(host[, port])'
     Connect to the server given by HOST and PORT.  See the intro for
     the default port.  This should be called directly only if the
     instance was instantiated without passing a host.

`send(data)'
     Send data to the server.  This should be used directly only after
     the `endheaders()' method has been called and before `getreply()'
     has been called.

`putrequest(request, selector)'
     This should be the first call after the connection to the server
     has been made.  It sends a line to the server consisting of the
     REQUEST string, the SELECTOR string, and the HTTP version
     (`HTTP/1.0').

`putheader(header, argument[, ...])'
     Send an RFC 822 style header to the server.  It sends a line to the
     server consisting of the header, a colon and a space, and the first
     argument.  If more arguments are given, continuation lines are
     sent, each consisting of a tab and an argument.

`endheaders()'
     Send a blank line to the server, signalling the end of the headers.

`getreply()'
     Complete the request by shutting down the sending end of the
     socket, read the reply from the server, and return a triple
     `(REPLYCODE, MESSAGE, HEADERS)'.  Here, REPLYCODE is the integer
     reply code from the request (e.g., `200' if the request was
     handled properly); MESSAGE is the message string corresponding to
     the reply code; and HEADERS is an instance of the class
     `mimetools.Message' containing the headers received from the
     server.  See the description of the `mimetools' module.

`getfile()'
     Return a file object from which the data returned by the server
     can be read, using the `read()', `readline()' or `readlines()'
     methods.


File: python-lib.info,  Node: HTTP Example,  Prev: HTTP Objects,  Up: httplib

Example
-------

   Here is an example session:

     >>> 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()


File: python-lib.info,  Node: ftplib,  Next: gopherlib,  Prev: httplib,  Up: Internet Protocols and Support

FTP protocol client
===================

   FTP protocol client (requires sockets).

   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:

     >>> 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.retrbinary('RETR README', open('README', 'wb').write)
     '226 Transfer complete.'
     >>> ftp.quit()

   The module defines the following items:

`FTP([host[, user[, passwd[, acct]]]])'
     Return a new instance of the `FTP' class.  When HOST is given, the
     method call `connect(HOST)' is made.  When USER is given,
     additionally the method call `login(USER, PASSWD, ACCT)' is made
     (where PASSWD and ACCT default to the empty string when not given).

`all_errors'
     The set of all exceptions (as a tuple) that methods of `FTP'
     instances may raise as a result of problems with the FTP connection
     (as opposed to programming errors made by the caller).  This set
     includes the four exceptions listed below as well as
     `socket.error' and `IOError'.

`error_reply'
     Exception raised when an unexpected reply is received from the
     server.

`error_temp'
     Exception raised when an error code in the range 400-499 is
     received.

`error_perm'
     Exception raised when an error code in the range 500-599 is
     received.

`error_proto'
     Exception raised when a reply is received from the server that does
     not begin with a digit in the range 1-5.

   See also:

   *Note netrc:: Parser for the `.netrc' file format.  The file
`.netrc' is typically used by FTP clients to load user authentication
information before prompting the user.  The file
`Tools/scripts/ftpmirror.py' in the Python source distribution is a
script that can mirror FTP sites, or portions thereof, using the
`ftplib' module. It can be used as an extended example that applies
this module.

* Menu:

* FTP Objects::


File: python-lib.info,  Node: FTP Objects,  Prev: ftplib,  Up: ftplib

FTP Objects
-----------

   Several methods are available in two flavors: one for handling text
files and another for binary files.  These are named for the command
which is used followed by `lines' for the text version or `binary' for
the binary version.

   `FTP' instances have the following methods:

`set_debuglevel(level)'
     Set the instance's debugging level.  This controls the amount of
     debugging output printed.  The default, `0', produces no debugging
     output.  A value of `1' produces a moderate amount of debugging
     output, generally a single line per request.  A value of `2' or
     higher produces the maximum amount of debugging output, logging
     each line sent and received on the control connection.

`connect(host[, port])'
     Connect to the given host and port.  The default port number is
     `21', as specified by the FTP protocol specification.  It is
     rarely needed to specify a different port number.  This function
     should be called only once for each instance; it should not be
     called at all if a host was given when the instance was created.
     All other methods can only be used after a connection has been
     made.

`getwelcome()'
     Return the welcome message sent by the server in reply to the
     initial connection.  (This message sometimes contains disclaimers
     or help information that may be relevant to the user.)

`login([user[, passwd[, acct]]])'
     Log in as the given USER.  The PASSWD and ACCT parameters are
     optional and default to the empty string.  If no USER is
     specified, it defaults to `'anonymous''.  If USER is
     `'anonymous'', the default PASSWD is `REALUSER@HOST' where
     REALUSER is the real user name (glanced from the `LOGNAME' or
     `USER' environment variable) and HOST is the hostname as returned
     by `socket.gethostname()'.  This function should be called only
     once for each instance, after a connection has been established; it
     should not be called at all if a host and user were given when the
     instance was created.  Most FTP commands are only allowed after the
     client has logged in.

`abort()'
     Abort a file transfer that is in progress.  Using this does not
     always work, but it's worth a try.

`sendcmd(command)'
     Send a simple command string to the server and return the response
     string.

`voidcmd(command)'
     Send a simple command string to the server and handle the response.
     Return nothing if a response code in the range 200-299 is received.
     Raise an exception otherwise.

`retrbinary(command, callback[, maxblocksize])'
     Retrieve a file in binary transfer mode.  COMMAND should be an
     appropriate `RETR' command, i.e. `'RETR FILENAME''.  The CALLBACK
     function is called for each block of data received, with a single
     string argument giving the data block.  The optional MAXBLOCKSIZE
     argument specifies the maximum chunk size to read on the low-level
     socket object created to do the actual transfer (which will also
     be the largest size of the data blocks passed to CALLBACK).  A
     reasonable default is chosen.

`retrlines(command[, callback])'
     Retrieve a file or directory listing in ASCII transfer mode.
     COMMAND should be an appropriate `RETR' command (see
     `retrbinary()' or a `LIST' command (usually just the string
     `'LIST'').  The CALLBACK function is called for each line, with
     the trailing CRLF stripped.  The default CALLBACK prints the line
     to `sys.stdout'.

`set_pasv(boolean)'
     Enable "passive" mode if BOOLEAN is true, other disable passive
     mode.

`storbinary(command, file, blocksize)'
     Store a file in binary transfer mode.  COMMAND should be an
     appropriate `STOR' command, i.e. `"STOR FILENAME"'.  FILE is an
     open file object which is read until `EOF' using its `read()'
     method in blocks of size BLOCKSIZE to provide the data to be
     stored.

`storlines(command, file)'
     Store a file in ASCII transfer mode.  COMMAND should be an
     appropriate `STOR' command (see `storbinary()').  Lines are read
     until `EOF' from the open file object FILE using its `readline()'
     method to privide the data to be stored.

`transfercmd(cmd)'
     Initiate a transfer over the data connection.  If the transfer is
     active, send a `PORT' command and the transfer command specified
     by CMD, and accept the connection.  If the server is passive, send
     a `PASV' command, connect to it, and start the transfer command.
     Either way, return the socket for the connection.

`ntransfercmd(cmd)'
     Like `transfercmd()', but returns a tuple of the data connection
     and the expected size of the data.  If the expected size could not
     be computed, `None' will be returned as the expected size.

`nlst(argument[, ...])'
     Return a list of files as returned by the `NLST' command.  The
     optional ARGUMENT is a directory to list (default is the current
     server directory).  Multiple arguments can be used to pass
     non-standard options to the `NLST' command.

`dir(argument[, ...])'
     Return a directory listing as returned by the `LIST' command, as a
     list of lines.  The optional ARGUMENT is a directory to list
     (default is the current server directory).  Multiple arguments can
     be used to pass non-standard options to the `LIST' command.  If the
     last argument is a function, it is used as a CALLBACK function as
     for `retrlines()'.

`rename(fromname, toname)'
     Rename file FROMNAME on the server to TONAME.

`delete(filename)'
     Remove the file named FILENAME from the server.  If successful,
     returns the text of the response, otherwise raises `error_perm' on
     permission errors or `error_reply' on other errors.

`cwd(pathname)'
     Set the current directory on the server.

`mkd(pathname)'
     Create a new directory on the server.

`pwd()'
     Return the pathname of the current directory on the server.

`rmd(dirname)'
     Remove the directory named DIRNAME on the server.

`size(filename)'
     Request the size of the file named FILENAME on the server.  On
     success, the size of the file is returned as an integer, otherwise
     `None' is returned.  Note that the `SIZE' command is not
     standardized, but is supported by many common server
     implementations.

`quit()'
     Send a `QUIT' command to the server and close the connection.
     This is the "polite" way to close a connection, but it may raise an
     exception of the server reponds with an error to the `QUIT'
     command.  This implies a call to the `close()' method which
     renders the `FTP' instance useless for subsequent calls (see
     below).

`close()'
     Close the connection unilaterally.  This should not be applied to
     an already closed connection (e.g. after a successful call to
     `quit()'.  After this call the `FTP' instance should not be used
     any more (i.e., after a call to `close()' or `quit()' you cannot
     reopen the connection by issueing another `login()' method).


File: python-lib.info,  Node: gopherlib,  Next: poplib,  Prev: ftplib,  Up: Internet Protocols and Support

Gopher protocol client
======================

   Gopher protocol client (requires sockets).

   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:

`send_selector(selector, host[, port])'
     Send a SELECTOR string to the gopher server at HOST and PORT
     (default `70').  Returns an open file object from which the
     returned document can be read.

`send_query(selector, query, host[, port])'
     Send a SELECTOR string and a QUERY string to a gopher server at
     HOST and PORT (default `70').  Returns an open file object from
     which the returned document can be read.

   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.


File: python-lib.info,  Node: poplib,  Next: imaplib,  Prev: gopherlib,  Up: Internet Protocols and Support

POP3 protocol client
====================

   POP3 protocol client (requires sockets).

   This module defines a class, `POP3', which encapsulates a connection
to an POP3 server and implements protocol as defined in RFC 1725.  The
`POP3' class supports both the minmal and optional command sets.

   A single class is provided by the `poplib' module:

`POP3(host[, port])'
     This class implements the actual POP3 protocol.  The connection is
     created when the instance is initialized.  If PORT is omitted, the
     standard POP3 port (110) is used.

   One exception is defined as an attribute of the `poplib' module:

`error_proto'
     Exception raised on any errors.  The reason for the exception is
     passed to the constructor as a string.

* Menu:

* POP3 Objects::
* POP3 Example::


File: python-lib.info,  Node: POP3 Objects,  Next: POP3 Example,  Prev: poplib,  Up: poplib

POP3 Objects
------------

   All POP3 commands are represented by methods of the same name, in
lower-case; most return the response text sent by the server.

   An `POP3' instance has the following methods:

`getwelcome()'
     Returns the greeting string sent by the POP3 server.

`user(username)'
     Send user commad, response should indicate that a password is
     required.

`pass_(password)'
     Send password, response includes message count and mailbox size.
     Note: the mailbox on the server is locked until `quit()' is called.

`apop(user, secret)'
     Use the more secure APOP authentication to log into the POP3
     server.

`rpop(user)'
     Use RPOP authentication (similar to UNIX r-commands) to log into
     POP3 server.

`stat()'
     Get mailbox status.  The result is a tuple of 2 integers:
     `(MESSAGE COUNT, MAILBOX SIZE)'.

`list([which])'
     Request message list, result is in the form `['response',
     ['mesg_num octets', ...]]'.  If WHICH is set, it is the message to
     list.

`retr(which)'
     Retrieve whole message number WHICH.  Result is in form
     `['response', ['line', ...], octets]'.

`dele(which)'
     Delete message number WHICH.

`rset()'
     Remove any deletion marks for the mailbox.

`noop()'
     Do nothing.  Might be used as a keep-alive.

`quit()'
     Signoff:  commit changes, unlock mailbox, drop connection.

`top(which, howmuch)'
     Retrieves the message header plus HOWMUCH lines of the message
     after the header of message number WHICH. Result is in form
     `['response', ['line', ...], octets]'.

`uidl([which])'
     Return message digest (unique id) list.  If WHICH is specified,
     result contains the unique id for that message in the form
     `'RESPONSE MESGNUM UID', otherwise result is list `['response',
     ['mesgnum uid', ...], octets]'.


File: python-lib.info,  Node: POP3 Example,  Prev: POP3 Objects,  Up: poplib

POP3 Example
------------

   Here is a minimal example (without error checking) that opens a
mailbox and retrieves and prints all messages:

     import getpass, poplib
     
     M = poplib.POP3('localhost')
     M.user(getpass.getuser())
     M.pass_(getpass.getpass())
     numMessages = len(M.list()[1])
     for i in range(numMessages):
         for j in M.retr(i+1)[1]:
             print j

   At the end of the module, there is a test section that contains a
more extensive example of usage.


File: python-lib.info,  Node: imaplib,  Next: nntplib,  Prev: poplib,  Up: Internet Protocols and Support

IMAP4 protocol client
=====================

   IMAP4 protocol client (requires sockets).  This module was
documented by Piers Lauder <piers@staff.cs.usyd.edu.au>.
This section was written by Piers Lauder <piers@staff.cs.usyd.edu.au>.
This module defines a class, `IMAP4', which encapsulates a connection
to an IMAP4 server and implements the IMAP4rev1 client protocol as
defined in RFC 2060. It is backward compatible with IMAP4 (RFC 1730)
servers, but note that the `STATUS' command is not supported in IMAP4.

   A single class is provided by the `imaplib' module:

`IMAP4([host[, port]])'
     This class implements the actual IMAP4 protocol.  The connection is
     created and protocol version (IMAP4 or IMAP4rev1) is determined
     when the instance is initialized.  If HOST is not specified, `'''
     (the local host) is used.  If PORT is omitted, the standard IMAP4
     port (143) is used.

   Two exceptions are defined as attributes of the `IMAP4' class:

`IMAP4.error'
     Exception raised on any errors.  The reason for the exception is
     passed to the constructor as a string.

`IMAP4.abort'
     IMAP4 server errors cause this exception to be raised.  This is a
     sub-class of `IMAP4.error'.  Note that closing the instance and
     instantiating a new one will usually allow recovery from this
     exception.

   The following utility functions are defined:

`Internaldate2tuple(datestr)'
     Converts an IMAP4 INTERNALDATE string to Coordinated Universal
     Time. Returns a `time' module tuple.

`Int2AP(num)'
     Converts an integer into a string representation using characters
     from the set [`A' .. `P'].

`ParseFlags(flagstr)'
     Converts an IMAP4 `FLAGS' response to a tuple of individual flags.

`Time2Internaldate(date_time)'
     Converts a `time' module tuple to an IMAP4 `INTERNALDATE'
     representation.  Returns a string in the form: `"DD-Mmm-YYYY
     HH:MM:SS +HHMM"' (including double-quotes).

* Menu:

* IMAP4 Objects::
* IMAP4 Example::


File: python-lib.info,  Node: IMAP4 Objects,  Next: IMAP4 Example,  Prev: imaplib,  Up: imaplib

IMAP4 Objects
-------------

   All IMAP4rev1 commands are represented by methods of the same name,
either upper-case or lower-case.

   Each command returns a tuple: `(TYPE, [DATA, ...])' where TYPE is
usually `'OK'' or `'NO'', and DATA is either the text from the command
response, or mandated results from the command.

   An `IMAP4' instance has the following methods:

`append(mailbox, flags, date_time, message)'
     Append message to named mailbox.

`authenticate(func)'
     Authenticate command -- requires response processing. This is
     currently unimplemented, and raises an exception.

`check()'
     Checkpoint mailbox on server.

`close()'
     Close currently selected mailbox. Deleted messages are removed from
     writable mailbox. This is the recommended command before `LOGOUT'.

`copy(message_set, new_mailbox)'
     Copy MESSAGE_SET messages onto end of NEW_MAILBOX.

`create(mailbox)'
     Create new mailbox named MAILBOX.

`delete(mailbox)'
     Delete old mailbox named MAILBOX.

`expunge()'
     Permanently remove deleted items from selected mailbox. Generates
     an `EXPUNGE' response for each deleted message. Returned data
     contains a list of `EXPUNGE' message numbers in order received.

`fetch(message_set, message_parts)'
     Fetch (parts of) messages. Returned data are tuples of message part
     envelope and data.

`list([directory[, pattern]])'
     List mailbox names in DIRECTORY matching PATTERN.  DIRECTORY
     defaults to the top-level mail folder, and PATTERN defaults to
     match anything.  Returned data contains a list of `LIST' responses.

`login(user, password)'
     Identify the client using a plaintext password.

`logout()'
     Shutdown connection to server. Returns server `BYE' response.

`lsub([directory[, pattern]])'
     List subscribed mailbox names in directory matching pattern.
     DIRECTORY defaults to the top level directory and PATTERN defaults
     to match any mailbox.  Returned data are tuples of message part
     envelope and data.

`recent()'
     Prompt server for an update. Returned data is `None' if no new
     messages, else value of `RECENT' response.

`rename(oldmailbox, newmailbox)'
     Rename mailbox named OLDMAILBOX to NEWMAILBOX.

`response(code)'
     Return data for response CODE if received, or `None'. Returns the
     given code, instead of the usual type.

`search(charset, criteria)'
     Search mailbox for matching messages. Returned data contains a
     space separated list of matching message numbers.

`select([mailbox[, readonly]])'
     Select a mailbox. Returned data is the count of messages in
     MAILBOX (`EXISTS' response).  The default MAILBOX is `'INBOX''.
     If the READONLY flag is set, modifications to the mailbox are not
     allowed.

`status(mailbox, names)'
     Request named status conditions for MAILBOX.

`store(message_set, command, flag_list)'
     Alters flag dispositions for messages in mailbox.

`subscribe(mailbox)'
     Subscribe to new mailbox.

`uid(command, args)'
     Execute command args with messages identified by UID, rather than
     message number. Returns response appropriate to command.

`unsubscribe(mailbox)'
     Unsubscribe from old mailbox.

`xatom(name[, arg1[, arg2]])'
     Allow simple extension commands notified by server in `CAPABILITY'
     response.

   The following attributes are defined on instances of `IMAP4':

`PROTOCOL_VERSION'
     The most recent supported protocol in the `CAPABILITY' response
     from the server.

`debug'
     Integer value to control debugging output.  The initialize value is
     taken from the module variable `Debug'.  Values greater than three
     trace each command.


File: python-lib.info,  Node: IMAP4 Example,  Prev: IMAP4 Objects,  Up: imaplib

IMAP4 Example
-------------

   Here is a minimal example (without error checking) that opens a
mailbox and retrieves and prints all messages:

     import getpass, imaplib, string
     M = imaplib.IMAP4()
     M.LOGIN(getpass.getuser(), getpass.getpass())
     M.SELECT()
     typ, data = M.SEARCH(None, 'ALL')
     for num in string.split(data[0]):
         typ, data = M.FETCH(num, '(RFC822)')
         print 'Message %s\n%s\n' % (num, data[0][1])
     M.LOGOUT()

   Note that IMAP4 message numbers change as the mailbox changes, so it
is highly advisable to use UIDs instead, with the UID command.

   At the end of the module, there is a test section that contains a
more extensive example of usage.

   See also:

   Documents describing the protocol, and sources and binaries for
servers implementing it, can all be found at the University of
Washington's *IMAP Information Center*
(`http://www.cac.washington.edu/imap/').


File: python-lib.info,  Node: nntplib,  Next: smtplib,  Prev: imaplib,  Up: Internet Protocols and Support

NNTP protocol client
====================

   NNTP protocol client (requires sockets).

   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:

     >>> 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):

     >>> 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(host[, port [, user[, password]]])'
     Return a new instance of the `NNTP' class, representing a
     connection to the NNTP server running on host HOST, listening at
     port PORT.  The default PORT is 119.  If the optional USER and
     PASSWORD are provided, the `AUTHINFO USER' and `AUTHINFO PASS'
     commands are used to identify and authenticate the user to the
     server.

`error_reply'
     Exception raised when an unexpected reply is received from the
     server.

`error_temp'
     Exception raised when an error code in the range 400-499 is
     received.

`error_perm'
     Exception raised when an error code in the range 500-599 is
     received.

`error_proto'
     Exception raised when a reply is received from the server that does
     not begin with a digit in the range 1-5.

* Menu:

* NNTP Objects::

