home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !ibrowse / files / pylibi-6 < prev    next >
Encoding:
GNU Info File  |  1996-11-14  |  49.5 KB  |  1,171 lines

  1. This is Info file pylibi, produced by Makeinfo-1.55 from the input file
  2. lib.texi.
  3.  
  4. This file describes the built-in types, exceptions and functions and the
  5. standard modules that come with the Python system.  It assumes basic
  6. knowledge about the Python language.  For an informal introduction to
  7. the language, see the Python Tutorial.  The Python Reference Manual
  8. gives a more formal definition of the language.  (These manuals are not
  9. yet available in INFO or Texinfo format.)
  10.  
  11. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The
  12. Netherlands.
  13.  
  14. All Rights Reserved
  15.  
  16. Permission to use, copy, modify, and distribute this software and its
  17. documentation for any purpose and without fee is hereby granted,
  18. provided that the above copyright notice appear in all copies and that
  19. both that copyright notice and this permission notice appear in
  20. supporting documentation, and that the names of Stichting Mathematisch
  21. Centrum or CWI or Corporation for National Research Initiatives or CNRI
  22. not be used in advertising or publicity pertaining to distribution of
  23. the software without specific, written prior permission.
  24.  
  25. While CWI is the initial source for this software, a modified version
  26. is made available by the Corporation for National Research Initiatives
  27. (CNRI) at the Internet address ftp://ftp.python.org.
  28.  
  29. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  30. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  31. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  32. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  33. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  34. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  35. ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  36. THIS SOFTWARE.
  37.  
  38. 
  39. File: pylibi,  Node: Installing your CGI script on a Unix system,  Next: Testing your CGI script,  Prev: Caring about security,  Up: cgi
  40.  
  41. Installing your CGI script on a Unix system
  42. -------------------------------------------
  43.  
  44. Read the documentation for your HTTP server and check with your local
  45. system administrator to find the directory where CGI scripts should be
  46. installed; usually this is in a directory `cgi-bin' in the server tree.
  47.  
  48. Make sure that your script is readable and executable by "others"; the
  49. Unix file mode should be 755 (use `chmod 755 filename').  Make sure
  50. that the first line of the script contains `#!' starting in column 1
  51. followed by the pathname of the Python interpreter, for instance:
  52.  
  53.          #!/usr/local/bin/python
  54.  
  55. Make sure the Python interpreter exists and is executable by "others".
  56.  
  57. Make sure that any files your script needs to read or write are
  58. readable or writable, respectively, by "others" - their mode should be
  59. 644 for readable and 666 for writable.  This is because, for security
  60. reasons, the HTTP server executes your script as user "nobody", without
  61. any special privileges.  It can only read (write, execute) files that
  62. everybody can read (write, execute).  The current directory at
  63. execution time is also different (it is usually the server's cgi-bin
  64. directory) and the set of environment variables is also different from
  65. what you get at login.  in particular, don't count on the shell's
  66. search path for executables (`$PATH') or the Python module search path
  67. (`$PYTHONPATH') to be set to anything interesting.
  68.  
  69. If you need to load modules from a directory which is not on Python's
  70. default module search path, you can change the path in your script,
  71. before importing other modules, e.g.:
  72.  
  73.          import sys
  74.          sys.path.insert(0, "/usr/home/joe/lib/python")
  75.          sys.path.insert(0, "/usr/local/lib/python")
  76.  
  77. (This way, the directory inserted last will be searched first!)
  78.  
  79. Instructions for non-Unix systems will vary; check your HTTP server's
  80. documentation (it will usually have a section on CGI scripts).
  81.  
  82. 
  83. File: pylibi,  Node: Testing your CGI script,  Next: Debugging CGI scripts,  Prev: Installing your CGI script on a Unix system,  Up: cgi
  84.  
  85. Testing your CGI script
  86. -----------------------
  87.  
  88. Unfortunately, a CGI script will generally not run when you try it from
  89. the command line, and a script that works perfectly from the command
  90. line may fail mysteriously when run from the server.  There's one
  91. reason why you should still test your script from the command line: if
  92. it contains a syntax error, the python interpreter won't execute it at
  93. all, and the HTTP server will most likely send a cryptic error to the
  94. client.
  95.  
  96. Assuming your script has no syntax errors, yet it does not work, you
  97. have no choice but to read the next section:
  98.  
  99. 
  100. File: pylibi,  Node: Debugging CGI scripts,  Next: Common problems and solutions,  Prev: Testing your CGI script,  Up: cgi
  101.  
  102. Debugging CGI scripts
  103. ---------------------
  104.  
  105. First of all, check for trivial installation errors - reading the
  106. section above on installing your CGI script carefully can save you a
  107. lot of time.  If you wonder whether you have understood the
  108. installation procedure correctly, try installing a copy of this module
  109. file (`cgi.py') as a CGI script.  When invoked as a script, the file
  110. will dump its environment and the contents of the form in HTML form.
  111. Give it the right mode etc, and send it a request.  If it's installed
  112. in the standard `cgi-bin' directory, it should be possible to send it a
  113. request by entering a URL into your browser of the form:
  114.  
  115.          http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
  116.  
  117. If this gives an error of type 404, the server cannot find the script -
  118. perhaps you need to install it in a different directory.  If it gives
  119. another error (e.g.  500), there's an installation problem that you
  120. should fix before trying to go any further.  If you get a nicely
  121. formatted listing of the environment and form content (in this example,
  122. the fields should be listed as "addr" with value "At Home" and "name"
  123. with value "Joe Blow"), the `cgi.py' script has been installed
  124. correctly.  If you follow the same procedure for your own script, you
  125. should now be able to debug it.
  126.  
  127. The next step could be to call the `cgi' module's test() function from
  128. your script: replace its main code with the single statement
  129.  
  130.          cgi.test()
  131.  
  132. This should produce the same results as those gotten from installing
  133. the `cgi.py' file itself.
  134.  
  135. When an ordinary Python script raises an unhandled exception (e.g.
  136. because of a typo in a module name, a file that can't be opened, etc.),
  137. the Python interpreter prints a nice traceback and exits.  While the
  138. Python interpreter will still do this when your CGI script raises an
  139. exception, most likely the traceback will end up in one of the HTTP
  140. server's log file, or be discarded altogether.
  141.  
  142. Fortunately, once you have managed to get your script to execute *some*
  143. code, it is easy to catch exceptions and cause a traceback to be
  144. printed.  The `test()' function below in this module is an example.
  145. Here are the rules:
  146.  
  147.   1. Import the traceback module (before entering the try-except!)
  148.  
  149.   2. Make sure you finish printing the headers and the blank line early
  150.  
  151.   3. Assign `sys.stderr' to `sys.stdout'
  152.  
  153.   4. Wrap all remaining code in a try-except statement
  154.  
  155.   5. In the except clause, call `traceback.print_exc()'
  156.  
  157. For example:
  158.  
  159.          import sys
  160.          import traceback
  161.          print "Content-type: text/html"
  162.          print
  163.          sys.stderr = sys.stdout
  164.          try:
  165.              ...your code here...
  166.          except:
  167.              print "\n\n<PRE>"
  168.              traceback.print_exc()
  169.  
  170. Notes: The assignment to `sys.stderr' is needed because the traceback
  171. prints to `sys.stderr'.  The `print "nn<PRE>"' statement is necessary to
  172. disable the word wrapping in HTML.
  173.  
  174. If you suspect that there may be a problem in importing the traceback
  175. module, you can use an even more robust approach (which only uses
  176. built-in modules):
  177.  
  178.          import sys
  179.          sys.stderr = sys.stdout
  180.          print "Content-type: text/plain"
  181.          print
  182.          ...your code here...
  183.  
  184. This relies on the Python interpreter to print the traceback.  The
  185. content type of the output is set to plain text, which disables all
  186. HTML processing.  If your script works, the raw HTML will be displayed
  187. by your client.  If it raises an exception, most likely after the first
  188. two lines have been printed, a traceback will be displayed.  Because no
  189. HTML interpretation is going on, the traceback will readable.
  190.  
  191. 
  192. File: pylibi,  Node: Common problems and solutions,  Prev: Debugging CGI scripts,  Up: cgi
  193.  
  194. Common problems and solutions
  195. -----------------------------
  196.  
  197.    * Most HTTP servers buffer the output from CGI scripts until the
  198.      script is completed.  This means that it is not possible to
  199.      display a progress report on the client's display while the script
  200.      is running.
  201.  
  202.    * Check the installation instructions above.
  203.  
  204.    * Check the HTTP server's log files.  (`tail -f logfile' in a
  205.      separate window may be useful!)
  206.  
  207.    * Always check a script for syntax errors first, by doing something
  208.      like `python script.py'.
  209.  
  210.    * When using any of the debugging techniques, don't forget to add
  211.      `import sys' to the top of the script.
  212.  
  213.    * When invoking external programs, make sure they can be found.
  214.      Usually, this means using absolute path names - `$PATH' is usually
  215.      not set to a very useful value in a CGI script.
  216.  
  217.    * When reading or writing external files, make sure they can be read
  218.      or written by every user on the system.
  219.  
  220.    * Don't try to give a CGI script a set-uid mode.  This doesn't work
  221.      on most systems, and is a security liability as well.
  222.  
  223. 
  224. File: pylibi,  Node: urllib,  Next: httplib,  Prev: cgi,  Up: Internet and WWW
  225.  
  226. Standard Module `urllib'
  227. ========================
  228.  
  229. This module provides a high-level interface for fetching data across
  230. the World-Wide Web.  In particular, the `urlopen' function is similar
  231. to the built-in function `open', but accepts URLs (Universal Resource
  232. Locators) instead of filenames.  Some restrictions apply -- it can only
  233. open URLs for reading, and no seek operations are available.
  234.  
  235. it defines the following public functions:
  236.  
  237.  - function of module urllib: urlopen (URL)
  238.      Open a network object denoted by a URL for reading.  If the URL
  239.      does not have a scheme identifier, or if it has `file:' as its
  240.      scheme identifier, this opens a local file; otherwise it opens a
  241.      socket to a server somewhere on the network.  If the connection
  242.      cannot be made, or if the server returns an error code, the
  243.      `IOError' exception is raised.  If all went well, a file-like
  244.      object is returned.  This supports the following methods:
  245.      `read()', `readline()', `readlines()', `fileno()', `close()' and
  246.      `info()'.  Except for the last one, these methods have the same
  247.      interface as for file objects -- see the section on File Objects
  248.      earlier in this manual.  (It's not a built-in file object,
  249.      however, so it can't be used at those few places where a true
  250.      built-in file object is required.)
  251.  
  252.      The `info()' method returns an instance of the class
  253.      `rfc822.Message' containing the headers received from the server,
  254.      if the protocol uses such headers (currently the only supported
  255.      protocol that uses this is HTTP).  See the description of the
  256.      `rfc822' module.
  257.  
  258.  - function of module urllib: urlretrieve (URL)
  259.      Copy a network object denoted by a URL to a local file, if
  260.      necessary.  If the URL points to a local file, or a valid cached
  261.      copy of the object exists, the object is not copied.  Return a
  262.      tuple (FILENAME, HEADERS) where FILENAME is the local file name
  263.      under which the object can be found, and HEADERS is either `None'
  264.      (for a local object) or whatever the `info()' method of the object
  265.      returned by `urlopen()' returned (for a remote object, possibly
  266.      cached).  Exceptions are the same as for `urlopen()'.
  267.  
  268.  - function of module urllib: urlcleanup ()
  269.      Clear the cache that may have been built up by previous calls to
  270.      `urlretrieve()'.
  271.  
  272.  - function of module urllib: quote (STRING[, ADDSAFE])
  273.      Replace special characters in STRING using the `%xx' escape.
  274.      Letters, digits, and the characters "`_,.-'" are never quoted.
  275.      The optional ADDSAFE parameter specifies additional characters
  276.      that should not be quoted -- its default value is `'/''.
  277.  
  278.      Example: `quote('/~conolly/')' yields `'/%7econnolly/''.
  279.  
  280.  - function of module urllib: unquote (STRING)
  281.      Replace `%xx' escapes by their single-character equivalent.
  282.  
  283.      Example: `unquote('/%7Econnolly/')' yields `'/~connolly/''.
  284.  
  285. Restrictions:
  286.  
  287.    * Currently, only the following protocols are supported: HTTP,
  288.      (versions 0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local
  289.      files.
  290.  
  291.    * The caching feature of `urlretrieve()' has been disabled until I
  292.      find the time to hack proper processing of Expiration time headers.
  293.  
  294.    * There should be a function to query whether a particular URL is in
  295.      the cache.
  296.  
  297.    * For backward compatibility, if a URL appears to point to a local
  298.      file but the file can't be opened, the URL is re-interpreted using
  299.      the FTP protocol.  This can sometimes cause confusing error
  300.      messages.
  301.  
  302.    * The `urlopen()' and `urlretrieve()' functions can cause
  303.      arbitrarily long delays while waiting for a network connection to
  304.      be set up.  This means that it is difficult to build an interactive
  305.      web client using these functions without using threads.
  306.  
  307.    * The data returned by `urlopen()' or `urlretrieve()' is the raw
  308.      data returned by the server.  This may be binary data (e.g. an
  309.      image), plain text or (for example) HTML.  The HTTP protocol
  310.      provides type information in the reply header, which can be
  311.      inspected by looking at the `Content-type' header.  For the Gopher
  312.      protocol, type information is encoded in the URL; there is
  313.      currently no easy way to extract it.  If the returned data is
  314.      HTML, you can use the module `htmllib' to parse it.
  315.  
  316.    * Although the `urllib' module contains (undocumented) routines to
  317.      parse and unparse URL strings, the recommended interface for URL
  318.      manipulation is in module `urlparse'.
  319.  
  320. 
  321. File: pylibi,  Node: httplib,  Next: ftplib,  Prev: urllib,  Up: Internet and WWW
  322.  
  323. Standard Module `httplib'
  324. =========================
  325.  
  326. This module defines a class which implements the client side of the
  327. HTTP protocol.  It is normally not used directly -- the module `urllib'
  328. uses it to handle URLs that use HTTP.
  329.  
  330. The module defines one class, `HTTP'.  An `HTTP' instance represents
  331. one transaction with an HTTP server.  It should be instantiated passing
  332. it a host and optional port number.  If no port number is passed, the
  333. port is extracted from the host string if it has the form `host:port',
  334. else the default HTTP port (80) is used.  If no host is passed, no
  335. connection is made, and the `connect' method should be used to connect
  336. to a server.  For example, the following calls all create instances
  337. that connect to the server at the same host and port:
  338.  
  339.      >>> h1 = httplib.HTTP('www.cwi.nl')
  340.      >>> h2 = httplib.HTTP('www.cwi.nl:80')
  341.      >>> h3 = httplib.HTTP('www.cwi.nl', 80)
  342.  
  343. Once an `HTTP' instance has been connected to an HTTP server, it should
  344. be used as follows:
  345.  
  346.   1. 1.  Make exactly one call to the `putrequest()' method.
  347.  
  348.   2. 2.  Make zero or more calls to the `putheader()' method.
  349.  
  350.   3. 3.  Call the `endheaders()' method (this can be omitted if step 4
  351.      makes no calls).
  352.  
  353.   4. 4.  Optional calls to the `send()' method.
  354.  
  355.   5. 5.  Call the `getreply()' method.
  356.  
  357.   6. 6.  Call the `getfile()' method and read the data off the file
  358.      object that it returns.
  359.  
  360.  
  361. * Menu:
  362.  
  363. * HTTP Objects::
  364. * HTTP Example::
  365.  
  366. 
  367. File: pylibi,  Node: HTTP Objects,  Next: HTTP Example,  Prev: httplib,  Up: httplib
  368.  
  369. HTTP Objects
  370. ------------
  371.  
  372. `HTTP' instances have the following methods:
  373.  
  374.  - Method on HTTP: set_debuglevel (LEVEL)
  375.      Set the debugging level (the amount of debugging output printed).
  376.      The default debug level is `0', meaning no debugging output is
  377.      printed.
  378.  
  379.  - Method on HTTP: connect (HOST[, PORT])
  380.      Connect to the server given by HOST and PORT.  See the intro for
  381.      the default port.  This should be called directly only if the
  382.      instance was instantiated without passing a host.
  383.  
  384.  - Method on HTTP: send (DATA)
  385.      Send data to the server.  This should be used directly only after
  386.      the `endheaders()' method has been called and before `getreply()'
  387.      has been called.
  388.  
  389.  - Method on HTTP: putrequest (REQUEST, SELECTOR)
  390.      This should be the first call after the connection to the server
  391.      has been made.  It sends a line to the server consisting of the
  392.      REQUEST string, the SELECTOR string, and the HTTP version
  393.      (`HTTP/1.0').
  394.  
  395.  - Method on HTTP: putheader (HEADER, ARGUMENT[, ...])
  396.      Send an RFC-822 style header to the server.  It sends a line to the
  397.      server consisting of the header, a colon and a space, and the first
  398.      argument.  If more arguments are given, continuation lines are
  399.      sent, each consisting of a tab and an argument.
  400.  
  401.  - Method on HTTP: endheaders ()
  402.      Send a blank line to the server, signalling the end of the headers.
  403.  
  404.  - Method on HTTP: getreply ()
  405.      Complete the request by shutting down the sending end of the
  406.      socket, read the reply from the server, and return a triple
  407.      (REPLYCODE, MESSAGE, HEADERS).  Here REPLYCODE is the integer
  408.      reply code from the request (e.g. `200' if the request was handled
  409.      properly); MESSAGE is the message string corresponding to the
  410.      reply code; and HEADER is an instance of the class
  411.      `rfc822.Message' containing the headers received from the server.
  412.      See the description of the `rfc822' module.
  413.  
  414.  - Method on HTTP: getfile ()
  415.      Return a file object from which the data returned by the server
  416.      can be read, using the `read()', `readline()' or `readlines()'
  417.      methods.
  418.  
  419. 
  420. File: pylibi,  Node: HTTP Example,  Prev: HTTP Objects,  Up: httplib
  421.  
  422. Example
  423. -------
  424.  
  425. Here is an example session:
  426.  
  427.      >>> import httplib
  428.      >>> h = httplib.HTTP('www.cwi.nl')
  429.      >>> h.putrequest('GET', '/index.html')
  430.      >>> h.putheader('Accept', 'text/html')
  431.      >>> h.putheader('Accept', 'text/plain')
  432.      >>> h.endheaders()
  433.      >>> errcode, errmsg, headers = h.getreply()
  434.      >>> print errcode # Should be 200
  435.      >>> f = h.getfile()
  436.      >>> data f.read() # Get the raw HTML
  437.      >>> f.close()
  438.      >>>
  439.  
  440. 
  441. File: pylibi,  Node: ftplib,  Next: gopherlib,  Prev: httplib,  Up: Internet and WWW
  442.  
  443. Standard Module `ftplib'
  444. ========================
  445.  
  446. This module defines the class `FTP' and a few related items.  The `FTP'
  447. class implements the client side of the FTP protocol.  You can use this
  448. to write Python programs that perform a variety of automated FTP jobs,
  449. such as mirroring other ftp servers.  It is also used by the module
  450. `urllib' to handle URLs that use FTP.  For more information on FTP
  451. (File Transfer Protocol), see Internet RFC 959.
  452.  
  453. Here's a sample session using the `ftplib' module:
  454.  
  455.      >>> from ftplib import FTP
  456.      >>> ftp = FTP('ftp.cwi.nl')   # connect to host, default port
  457.      >>> ftp.login()               # user anonymous, passwd user@hostname
  458.      >>> ftp.retrlines('LIST')     # list directory contents
  459.      total 24418
  460.      drwxrwsr-x   5 ftp-usr  pdmaint     1536 Mar 20 09:48 .
  461.      dr-xr-srwt 105 ftp-usr  pdmaint     1536 Mar 21 14:32 ..
  462.      -rw-r--r--   1 ftp-usr  pdmaint     5305 Mar 20 09:48 INDEX
  463.       .
  464.       .
  465.       .
  466.      >>> ftp.quit()
  467.  
  468. The module defines the following items:
  469.  
  470.  - function of module ftplib: FTP ([HOST[, USER, PASSWD, ACCT]])
  471.      Return a new instance of the `FTP' class.  When HOST is given, the
  472.      method call `connect(HOST)' is made.  When USER is given,
  473.      additionally the method call `login(USER, PASSWD, ACCT)' is made
  474.      (where PASSWD and ACCT default to the empty string when not given).
  475.  
  476.  - data of module ftplib: all_errors
  477.      The set of all exceptions (as a tuple) that methods of `FTP'
  478.      instances may raise as a result of problems with the FTP connection
  479.      (as opposed to programming errors made by the caller).  This set
  480.      includes the four exceptions listed below as well as
  481.      `socket.error' and `IOError'.
  482.  
  483.  - exception of module ftplib: error_reply
  484.      Exception raised when an unexpected reply is received from the
  485.      server.
  486.  
  487.  - exception of module ftplib: error_temp
  488.      Exception raised when an error code in the range 400-499 is
  489.      received.
  490.  
  491.  - exception of module ftplib: error_perm
  492.      Exception raised when an error code in the range 500-599 is
  493.      received.
  494.  
  495.  - exception of module ftplib: error_proto
  496.      Exception raised when a reply is received from the server that does
  497.      not begin with a digit in the range 1-5.
  498.  
  499. * Menu:
  500.  
  501. * FTP Objects::
  502.  
  503. 
  504. File: pylibi,  Node: FTP Objects,  Prev: ftplib,  Up: ftplib
  505.  
  506. FTP Objects
  507. -----------
  508.  
  509. FTP instances have the following methods:
  510.  
  511.  - Method on FTP object: set_debuglevel (LEVEL)
  512.      Set the instance's debugging level.  This controls the amount of
  513.      debugging output printed.  The default, 0, produces no debugging
  514.      output.  A value of 1 produces a moderate amount of debugging
  515.      output, generally a single line per request.  A value of 2 or
  516.      higher produces the maximum amount of debugging output, logging
  517.      each line sent and received on the control connection.
  518.  
  519.  - Method on FTP object: connect (HOST[, PORT])
  520.      Connect to the given host and port.  The default port number is
  521.      21, as specified by the FTP protocol specification.  It is rarely
  522.      needed to specify a different port number.  This function should
  523.      be called only once for each instance; it should not be called at
  524.      all if a host was given when the instance was created.  All other
  525.      methods can only be used after a connection has been made.
  526.  
  527.  - Method on FTP object: getwelcome ()
  528.      Return the welcome message sent by the server in reply to the
  529.      initial connection.  (This message sometimes contains disclaimers
  530.      or help information that may be relevant to the user.)
  531.  
  532.  - Method on FTP object: login ([USER[, PASSWD[, ACCT]]])
  533.      Log in as the given USER.  The PASSWD and ACCT parameters are
  534.      optional and default to the empty string.  If no USER is
  535.      specified, it defaults to `anonymous'.  If USER is `anonymous',
  536.      the default PASSWD is `REALUSER@HOST' where REALUSER is the real
  537.      user name (glanced from the `LOGNAME' or `USER' environment
  538.      variable) and HOST is the hostname as returned by
  539.      `socket.gethostname()'.  This function should be called only once
  540.      for each instance, after a connection has been established; it
  541.      should not be called at all if a host and user were given when the
  542.      instance was created.  Most FTP commands are only allowed after the
  543.      client has logged in.
  544.  
  545.  - Method on FTP object: abort ()
  546.      Abort a file transfer that is in progress.  Using this does not
  547.      always work, but it's worth a try.
  548.  
  549.  - Method on FTP object: sendcmd (COMMAND)
  550.      Send a simple command string to the server and return the response
  551.      string.
  552.  
  553.  - Method on FTP object: voidcmd (COMMAND)
  554.      Send a simple command string to the server and handle the response.
  555.      Return nothing if a response code in the range 200-299 is received.
  556.      Raise an exception otherwise.
  557.  
  558.  - Method on FTP object: retrbinary (COMMAND, CALLBACK, MAXBLOCKSIZE)
  559.      Retrieve a file in binary transfer mode.  COMMAND should be an
  560.      appropriate `RETR' command, i.e. `"RETR FILENAME"'.  The CALLBACK
  561.      function is called for each block of data received, with a single
  562.      string argument giving the data block.  The MAXBLOCKSIZE argument
  563.      specifies the maximum block size (which may not be the actual size
  564.      of the data blocks passed to CALLBACK).
  565.  
  566.  - Method on FTP object: retrlines (COMMAND[, CALLBACK])
  567.      Retrieve a file or directory listing in ASCII transfer mode.
  568.      varcommand should be an appropriate `RETR' command (see
  569.      `retrbinary()' or a `LIST' command (usually just the string
  570.      `"LIST"').  The CALLBACK function is called for each line, with
  571.      the trailing CRLF stripped.  The default CALLBACK prints the line
  572.      to `sys.stdout'.
  573.  
  574.  - Method on FTP object: storbinary (COMMAND, FILE, BLOCKSIZE)
  575.      Store a file in binary transfer mode.  COMMAND should be an
  576.      appropriate `STOR' command, i.e. `"STOR FILENAME"'.  FILE is an
  577.      open file object which is read until EOF using its `read()' method
  578.      in blocks of size BLOCKSIZE to provide the data to be stored.
  579.  
  580.  - Method on FTP object: storlines (COMMAND, FILE)
  581.      Store a file in ASCII transfer mode.  COMMAND should be an
  582.      appropriate `STOR' command (see `storbinary()').  Lines are read
  583.      until EOF from the open file object FILE using its `readline()'
  584.      method to privide the data to be stored.
  585.  
  586.  - Method on FTP object: nlst (ARGUMENT[, ...])
  587.      Return a list of files as returned by the `NLST' command.  The
  588.      optional varargument is a directory to list (default is the current
  589.      server directory).  Multiple arguments can be used to pass
  590.      non-standard options to the `NLST' command.
  591.  
  592.  - Method on FTP object: dir (ARGUMENT[, ...])
  593.      Return a directory listing as returned by the `LIST' command, as a
  594.      list of lines.  The optional varargument is a directory to list
  595.      (default is the current server directory).  Multiple arguments can
  596.      be used to pass non-standard options to the `LIST' command.  If the
  597.      last argument is a function, it is used as a CALLBACK function as
  598.      for `retrlines()'.
  599.  
  600.  - Method on FTP object: rename (FROMNAME, TONAME)
  601.      Rename file FROMNAME on the server to TONAME.
  602.  
  603.  - Method on FTP object: cwd (PATHNAME)
  604.      Set the current directory on the server.
  605.  
  606.  - Method on FTP object: mkd (PATHNAME)
  607.      Create a new directory on the server.
  608.  
  609.  - Method on FTP object: pwd ()
  610.      Return the pathname of the current directory on the server.
  611.  
  612.  - Method on FTP object: quit ()
  613.      Send a `QUIT' command to the server and close the connection.
  614.      This is the "polite" way to close a connection, but it may raise an
  615.      exception of the server reponds with an error to the `QUIT'
  616.      command.
  617.  
  618.  - Method on FTP object: close ()
  619.      Close the connection unilaterally.  This should not be applied to
  620.      an already closed connection (e.g. after a successful call to
  621.      `quit()'.
  622.  
  623. 
  624. File: pylibi,  Node: gopherlib,  Next: nntplib,  Prev: ftplib,  Up: Internet and WWW
  625.  
  626. Standard Module `gopherlib'
  627. ===========================
  628.  
  629. This module provides a minimal implementation of client side of the the
  630. Gopher protocol.  It is used by the module `urllib' to handle URLs that
  631. use the Gopher protocol.
  632.  
  633. The module defines the following functions:
  634.  
  635.  - function of module gopherlib: send_selector (SELECTOR, HOST[, PORT])
  636.      Send a SELECTOR string to the gopher server at HOST and PORT
  637.      (default 70).  Return an open file object from which the returned
  638.      document can be read.
  639.  
  640.  - function of module gopherlib: send_query (SELECTOR, QUERY, HOST[,
  641.           PORT])
  642.      Send a SELECTOR string and a QUERY string to a gopher server at
  643.      HOST and PORT (default 70).  Return an open file object from which
  644.      the returned document can be read.
  645.  
  646. Note that the data returned by the Gopher server can be of any type,
  647. depending on the first character of the selector string.  If the data
  648. is text (first character of the selector is `0'), lines are terminated
  649. by CRLF, and the data is terminated by a line consisting of a single
  650. `.', and a leading `.' should be stripped from lines that begin with
  651. `..'.  Directory listings (first charactger of the selector is `1') are
  652. transferred using the same protocol.
  653.  
  654. 
  655. File: pylibi,  Node: nntplib,  Next: urlparse,  Prev: gopherlib,  Up: Internet and WWW
  656.  
  657. Standard Module `nntplib'
  658. =========================
  659.  
  660. This module defines the class `NNTP' which implements the client side
  661. of the NNTP protocol.  It can be used to implement a news reader or
  662. poster, or automated news processors.  For more information on NNTP
  663. (Network News Transfer Protocol), see Internet RFC 977.
  664.  
  665. Here are two small examples of how it can be used.  To list some
  666. statistics about a newsgroup and print the subjects of the last 10
  667. articles:
  668.  
  669.      >>> s = NNTP('news.cwi.nl')
  670.      >>> resp, count, first, last, name = s.group('comp.lang.python')
  671.      >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
  672.      Group comp.lang.python has 59 articles, range 3742 to 3803
  673.      >>> resp, subs = s.xhdr('subject', first + '-' + last)
  674.      >>> for id, sub in subs[-10:]: print id, sub
  675.      ...
  676.      3792 Re: Removing elements from a list while iterating...
  677.      3793 Re: Who likes Info files?
  678.      3794 Emacs and doc strings
  679.      3795 a few questions about the Mac implementation
  680.      3796 Re: executable python scripts
  681.      3797 Re: executable python scripts
  682.      3798 Re: a few questions about the Mac implementation
  683.      3799 Re: PROPOSAL: A Generic Python Object Interface for Python C Modules
  684.      3802 Re: executable python scripts
  685.      3803 Re: POSIX wait and SIGCHLD
  686.      >>> s.quit()
  687.      '205 news.cwi.nl closing connection.  Goodbye.'
  688.      >>>
  689.  
  690. To post an article from a file (this assumes that the article has valid
  691. headers):
  692.  
  693.      >>> s = NNTP('news.cwi.nl')
  694.      >>> f = open('/tmp/article')
  695.      >>> s.post(f)
  696.      '240 Article posted successfully.'
  697.      >>> s.quit()
  698.      '205 news.cwi.nl closing connection.  Goodbye.'
  699.      >>>
  700.  
  701. The module itself defines the following items:
  702.  
  703.  - function of module nntplib: NNTP (HOST[, PORT])
  704.      Return a new instance of the `NNTP' class, representing a
  705.      connection to the NNTP server running on host HOST, listening at
  706.      port PORT.  The default PORT is 119.
  707.  
  708.  - exception of module nntplib: error_reply
  709.      Exception raised when an unexpected reply is received from the
  710.      server.
  711.  
  712.  - exception of module nntplib: error_temp
  713.      Exception raised when an error code in the range 400-499 is
  714.      received.
  715.  
  716.  - exception of module nntplib: error_perm
  717.      Exception raised when an error code in the range 500-599 is
  718.      received.
  719.  
  720.  - exception of module nntplib: error_proto
  721.      Exception raised when a reply is received from the server that does
  722.      not begin with a digit in the range 1-5.
  723.  
  724. * Menu:
  725.  
  726. * NNTP Objects::
  727.  
  728. 
  729. File: pylibi,  Node: NNTP Objects,  Prev: nntplib,  Up: nntplib
  730.  
  731. NNTP Objects
  732. ------------
  733.  
  734. NNTP instances have the following methods.  The RESPONSE that is
  735. returned as the first item in the return tuple of almost all methods is
  736. the server's response: a string beginning with a three-digit code.  If
  737. the server's response indicates an error, the method raises one of the
  738. above exceptions.
  739.  
  740.  - Method on NNTP object: getwelcome ()
  741.      Return the welcome message sent by the server in reply to the
  742.      initial connection.  (This message sometimes contains disclaimers
  743.      or help information that may be relevant to the user.)
  744.  
  745.  - Method on NNTP object: set_debuglevel (LEVEL)
  746.      Set the instance's debugging level.  This controls the amount of
  747.      debugging output printed.  The default, 0, produces no debugging
  748.      output.  A value of 1 produces a moderate amount of debugging
  749.      output, generally a single line per request or response.  A value
  750.      of 2 or higher produces the maximum amount of debugging output,
  751.      logging each line sent and received on the connection (including
  752.      message text).
  753.  
  754.  - Method on NNTP object: newgroups (DATE, TIME)
  755.      Send a `NEWGROUPS' command.  The DATE argument should be a string
  756.      of the form `"YYMMDD"' indicating the date, and TIME should be a
  757.      string of the form `"HHMMSS"' indicating the time.  Return a pair
  758.      `(RESPONSE, GROUPS)' where GROUPS is a list of group names that
  759.      are new since the given date and time.
  760.  
  761.  - Method on NNTP object: newnews (GROUP, DATE, TIME)
  762.      Send a `NEWNEWS' command.  Here, GROUP is a group name or `"*"',
  763.      and DATE and TIME have the same meaning as for `newgroups()'.
  764.      Return a pair `(RESPONSE, ARTICLES)' where ARTICLES is a list of
  765.      article ids.
  766.  
  767.  - Method on NNTP object: list ()
  768.      Send a `LIST' command.  Return a pair `(RESPONSE, LIST)' where
  769.      LIST is a list of tuples.  Each tuple has the form `(GROUP, LAST,
  770.      FIRST, FLAG)', where GROUP is a group name, LAST and FIRST are the
  771.      last and first article numbers (as strings), and FLAG is `'y'' if
  772.      posting is allowed, `'n'' if not, and `'m'' if the newsgroup is
  773.      moderated.  (Note the ordering: LAST, FIRST.)
  774.  
  775.  - Method on NNTP object: group (NAME)
  776.      Send a `GROUP' command, where NAME is the group name.  Return a
  777.      tuple `(RESPONSE, COUNT, FIRST, LAST, NAME)' where COUNT is the
  778.      (estimated) number of articles in the group, FIRST is the first
  779.      article number in the group, LAST is the last article number in
  780.      the group, and NAME is the group name.  The numbers are returned
  781.      as strings.
  782.  
  783.  - Method on NNTP object: help ()
  784.      Send a `HELP' command.  Return a pair `(RESPONSE, LIST)' where
  785.      LIST is a list of help strings.
  786.  
  787.  - Method on NNTP object: stat (ID)
  788.      Send a `STAT' command, where ID is the message id (enclosed in `<'
  789.      and `>') or an article number (as a string).  Return a triple
  790.      `(varresponse, NUMBER, ID)' where NUMBER is the article number (as
  791.      a string) and ID is the article id  (enclosed in `<' and `>').
  792.  
  793.  - Method on NNTP object: next ()
  794.      Send a `NEXT' command.  Return as for `stat()'.
  795.  
  796.  - Method on NNTP object: last ()
  797.      Send a `LAST' command.  Return as for `stat()'.
  798.  
  799.  - Method on NNTP object: head (ID)
  800.      Send a `HEAD' command, where ID has the same meaning as for
  801.      `stat()'.  Return a pair `(RESPONSE, LIST)' where LIST is a list
  802.      of the article's headers (an uninterpreted list of lines, without
  803.      trailing newlines).
  804.  
  805.  - Method on NNTP object: body (ID)
  806.      Send a `BODY' command, where ID has the same meaning as for
  807.      `stat()'.  Return a pair `(RESPONSE, LIST)' where LIST is a list
  808.      of the article's body text (an uninterpreted list of lines,
  809.      without trailing newlines).
  810.  
  811.  - Method on NNTP object: article (ID)
  812.      Send a `ARTICLE' command, where ID has the same meaning as for
  813.      `stat()'.  Return a pair `(RESPONSE, LIST)' where LIST is a list
  814.      of the article's header and body text (an uninterpreted list of
  815.      lines, without trailing newlines).
  816.  
  817.  - Method on NNTP object: slave ()
  818.      Send a `SLAVE' command.  Return the server's RESPONSE.
  819.  
  820.  - Method on NNTP object: xhdr (HEADER, STRING)
  821.      Send an `XHDR' command.  This command is not defined in the RFC
  822.      but is a common extension.  The HEADER argument is a header
  823.      keyword, e.g. `"subject"'.  The STRING argument should have the
  824.      form `"FIRST-LAST"' where FIRST and LAST are the first and last
  825.      article numbers to search.  Return a pair `(RESPONSE, LIST)',
  826.      where LIST is a list of pairs `(ID, TEXT)', where ID is an article
  827.      id (as a string) and TEXT is the text of the requested header for
  828.      that article.
  829.  
  830.  - Method on NNTP object: post (FILE)
  831.      Post an article using the `POST' command.  The FILE argument is an
  832.      open file object which is read until EOF using its `readline()'
  833.      method.  It should be a well-formed news article, including the
  834.      required headers.  The `post()' method automatically escapes lines
  835.      beginning with `.'.
  836.  
  837.  - Method on NNTP object: ihave (ID, FILE)
  838.      Send an `IHAVE' command.  If the response is not an error, treat
  839.      FILE exactly as for the `post()' method.
  840.  
  841.  - Method on NNTP object: quit ()
  842.      Send a `QUIT' command and close the connection.  Once this method
  843.      has been called, no other methods of the NNTP object should be
  844.      called.
  845.  
  846. 
  847. File: pylibi,  Node: urlparse,  Next: sgmllib,  Prev: nntplib,  Up: Internet and WWW
  848.  
  849. Standard Module `urlparse'
  850. ==========================
  851.  
  852. This module defines a standard interface to break URL strings up in
  853. components (addessing scheme, network location, path etc.), to combine
  854. the components back into a URL string, and to convert a "relative URL"
  855. to an absolute URL given a "base URL".
  856.  
  857. The module has been designed to match the current Internet draft on
  858. Relative Uniform Resource Locators (and discovered a bug in an earlier
  859. draft!).
  860.  
  861. It defines the following functions:
  862.  
  863.  - function of module urlparse: urlparse (URLSTRING[, DEFAULT_SCHEME[,
  864.           ALLOW_FRAGMENTS]])
  865.      Parse a URL into 6 components, returning a 6-tuple: (addressing
  866.      scheme, network location, path, parameters, query, fragment
  867.      identifier).  This corresponds to the general structure of a URL:
  868.      `SCHEME://NETLOC/PATH;PARAMETERS?QUERY#FRAGMENT'.  Each tuple item
  869.      is a string, possibly empty.  The components are not broken up in
  870.      smaller parts (e.g. the network location is a single string), and
  871.      % escapes are not expanded.  The delimiters as shown above are not
  872.      part of the tuple items, except for a leading slash in the PATH
  873.      component, which is retained if present.
  874.  
  875.      Example:
  876.  
  877.           urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
  878.  
  879.      yields the tuple
  880.  
  881.           ('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '')
  882.  
  883.      If the DEFAULT_SCHEME argument is specified, it gives the default
  884.      addressing scheme, to be used only if the URL string does not
  885.      specify one.  The default value for this argument is the empty
  886.      string.
  887.  
  888.      If the ALLOW_FRAGMENTS argument is zero, fragment identifiers are
  889.      not allowed, even if the URL's addressing scheme normally does
  890.      support them.  The default value for this argument is `1'.
  891.  
  892.  - function of module urlparse: urlunparse (TUPLE)
  893.      Construct a URL string from a tuple as returned by `urlparse'.
  894.      This may result in a slightly different, but equivalent URL, if the
  895.      URL that was parsed originally had redundant delimiters, e.g. a ?
  896.      with an empty query (the draft states that these are equivalent).
  897.  
  898.  - function of module urlparse: urljoin (BASE, URL[, ALLOW_FRAGMENTS])
  899.      Construct a full ("absolute") URL by combining a "base URL" (BASE)
  900.      with a "relative URL" (URL).  Informally, this uses components of
  901.      the base URL, in particular the addressing scheme, the network
  902.      location and (part of) the path, to provide missing components in
  903.      the relative URL.
  904.  
  905.      Example:
  906.  
  907.           urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
  908.  
  909.      yields the string
  910.  
  911.           'http://www.cwi.nl/%7Eguido/FAQ.html'
  912.  
  913.      The ALLOW_FRAGMENTS argument has the same meaning as for
  914.      `urlparse'.
  915.  
  916. 
  917. File: pylibi,  Node: sgmllib,  Next: htmllib,  Prev: urlparse,  Up: Internet and WWW
  918.  
  919. Standard Module `sgmllib'
  920. =========================
  921.  
  922. This module defines a class `SGMLParser' which serves as the basis for
  923. parsing text files formatted in SGML (Standard Generalized Mark-up
  924. Language).  In fact, it does not provide a full SGML parser -- it only
  925. parses SGML insofar as it is used by HTML, and the module only exists
  926. as a base for the `htmllib' module.
  927.  
  928. In particular, the parser is hardcoded to recognize the following
  929. constructs:
  930.  
  931.    * Opening and closing tags of the form "`<TAG ATTR="VALUE" ...>'" and
  932.      "`</TAG>'", respectively.
  933.  
  934.    * Numeric character references of the form "`&#NAME;'".
  935.  
  936.    * Entity references of the form "`&NAME;'".
  937.  
  938.    * SGML comments of the form "`<!--TEXT-->'".  Note that spaces,
  939.      tabs, and newlines are allowed between the trailing "`>'" and the
  940.      immediately preceeding "`--'".
  941.  
  942. The `SGMLParser' class must be instantiated without arguments.  It has
  943. the following interface methods:
  944.  
  945.  - Method on SGMLParser: reset ()
  946.      Reset the instance.  Loses all unprocessed data.  This is called
  947.      implicitly at instantiation time.
  948.  
  949.  - Method on SGMLParser: setnomoretags ()
  950.      Stop processing tags.  Treat all following input as literal input
  951.      (CDATA).  (This is only provided so the HTML tag `<PLAINTEXT>' can
  952.      be implemented.)
  953.  
  954.  - Method on SGMLParser: setliteral ()
  955.      Enter literal mode (CDATA mode).
  956.  
  957.  - Method on SGMLParser: feed (DATA)
  958.      Feed some text to the parser.  It is processed insofar as it
  959.      consists of complete elements; incomplete data is buffered until
  960.      more data is fed or `close()' is called.
  961.  
  962.  - Method on SGMLParser: close ()
  963.      Force processing of all buffered data as if it were followed by an
  964.      end-of-file mark.  This method may be redefined by a derived class
  965.      to define additional processing at the end of the input, but the
  966.      redefined version should always call `SGMLParser.close()'.
  967.  
  968.  - Method on SGMLParser: handle_starttag (TAG, METHOD, ATTRIBUTES)
  969.      This method is called to handle start tags for which either a
  970.      `start_TAG()' or `do_TAG()' method has been defined.  The `tag'
  971.      argument is the name of the tag converted to lower case, and the
  972.      `method' argument is the bound method which should be used to
  973.      support semantic interpretation of the start tag.  The ATTRIBUTES
  974.      argument is a list of (NAME, VALUE) pairs containing the
  975.      attributes found inside the tag's `<>' brackets.  The NAME has
  976.      been translated to lower case and double quotes and backslashes in
  977.      the VALUE have been interpreted.  For instance, for the tag `<A
  978.      HREF="http://www.cwi.nl/">', this method would be called as
  979.      `unknown_starttag('a', [('href', 'http://www.cwi.nl/')])'.  The
  980.      base implementation simply calls `method' with `attributes' as the
  981.      only argument.
  982.  
  983.  - Method on SGMLParser: handle_endtag (TAG, METHOD)
  984.      This method is called to handle endtags for which an `end_TAG()'
  985.      method has been defined.  The `tag' argument is the name of the
  986.      tag converted to lower case, and the `method' argument is the
  987.      bound method which should be used to support semantic
  988.      interpretation of the end tag.  If no `end_TAG()' method is
  989.      defined for the closing element, this handler is not called.  The
  990.      base implementation simply calls `method'.
  991.  
  992.  - Method on SGMLParser: handle_data (DATA)
  993.      This method is called to process arbitrary data.  It is intended
  994.      to be overridden by a derived class; the base class implementation
  995.      does nothing.
  996.  
  997.  - Method on SGMLParser: handle_charref (REF)
  998.      This method is called to process a character reference of the form
  999.      "`&#REF;'".  In the base implementation, REF must be a decimal
  1000.      number in the range 0-255.  It translates the character to ASCII
  1001.      and calls the method `handle_data()' with the character as
  1002.      argument.  If REF is invalid or out of range, the method
  1003.      `unknown_charref(REF)' is called to handle the error.  A subclass
  1004.      must override this method to provide support for named character
  1005.      entities.
  1006.  
  1007.  - Method on SGMLParser: handle_entityref (REF)
  1008.      This method is called to process a general entity reference of the
  1009.      form "`&REF;'" where REF is an general entity reference.  It looks
  1010.      for REF in the instance (or class) variable `entitydefs' which
  1011.      should be a mapping from entity names to corresponding
  1012.      translations.  If a translation is found, it calls the method
  1013.      `handle_data()' with the translation; otherwise, it calls the
  1014.      method `unknown_entityref(REF)'.  The default `entitydefs' defines
  1015.      translations for `&', `&apos', `>', `<', and `"'.
  1016.  
  1017.  - Method on SGMLParser: handle_comment (COMMENT)
  1018.      This method is called when a comment is encountered.  The
  1019.      `comment' argument is a string containing the text between the
  1020.      "`<!--'" and "`-->'" delimiters, but not the delimiters
  1021.      themselves.  For example, the comment "`<!--text-->'" will cause
  1022.      this method to be called with the argument `'text''.  The default
  1023.      method does nothing.
  1024.  
  1025.  - Method on SGMLParser: report_unbalanced (TAG)
  1026.      This method is called when an end tag is found which does not
  1027.      correspond to any open element.
  1028.  
  1029.  - Method on SGMLParser: unknown_starttag (TAG, ATTRIBUTES)
  1030.      This method is called to process an unknown start tag.  It is
  1031.      intended to be overridden by a derived class; the base class
  1032.      implementation does nothing.
  1033.  
  1034.  - Method on SGMLParser: unknown_endtag (TAG)
  1035.      This method is called to process an unknown end tag.  It is
  1036.      intended to be overridden by a derived class; the base class
  1037.      implementation does nothing.
  1038.  
  1039.  - Method on SGMLParser: unknown_charref (REF)
  1040.      This method is called to process unresolvable numeric character
  1041.      references.  It is intended to be overridden by a derived class;
  1042.      the base class implementation does nothing.
  1043.  
  1044.  - Method on SGMLParser: unknown_entityref (REF)
  1045.      This method is called to process an unknown entity reference.  It
  1046.      is intended to be overridden by a derived class; the base class
  1047.      implementation does nothing.
  1048.  
  1049. Apart from overriding or extending the methods listed above, derived
  1050. classes may also define methods of the following form to define
  1051. processing of specific tags.  Tag names in the input stream are case
  1052. independent; the TAG occurring in method names must be in lower case:
  1053.  
  1054.  - Method on SGMLParser: start_TAG (ATTRIBUTES)
  1055.      This method is called to process an opening tag TAG.  It has
  1056.      preference over `do_TAG()'.  The ATTRIBUTES argument has the same
  1057.      meaning as described for `handle_starttag()' above.
  1058.  
  1059.  - Method on SGMLParser: do_TAG (ATTRIBUTES)
  1060.      This method is called to process an opening tag TAG that does not
  1061.      come with a matching closing tag.  The ATTRIBUTES argument has the
  1062.      same meaning as described for `handle_starttag()' above.
  1063.  
  1064.  - Method on SGMLParser: end_TAG ()
  1065.      This method is called to process a closing tag TAG.
  1066.  
  1067. Note that the parser maintains a stack of open elements for which no
  1068. end tag has been found yet.  Only tags processed by `start_TAG()' are
  1069. pushed on this stack.  Definition of an `end_TAG()' method is optional
  1070. for these tags.  For tags processed by `do_TAG()' or by
  1071. `unknown_tag()', no `end_TAG()' method must be defined; if defined, it
  1072. will not be used.  If both `start_TAG()' and `do_TAG()' methods exist
  1073. for a tag, the `start_TAG()' method takes precedence.
  1074.  
  1075. 
  1076. File: pylibi,  Node: htmllib,  Next: formatter,  Prev: sgmllib,  Up: Internet and WWW
  1077.  
  1078. Standard Module `htmllib'
  1079. =========================
  1080.  
  1081. This module defines a class which can serve as a base for parsing text
  1082. files formatted in the HyperText Mark-up Language (HTML).  The class is
  1083. not directly concerned with I/O -- it must be provided with input in
  1084. string form via a method, and makes calls to methods of a "formatter"
  1085. object in order to produce output.  The `HTMLParser' class is designed
  1086. to be used as a base class for other classes in order to add
  1087. functionality, and allows most of its methods to be extended or
  1088. overridden.  In turn, this class is derived from and extends the
  1089. `SGMLParser' class defined in module `sgmllib'.  Two implementations of
  1090. formatter objects are provided in the `formatter' module; refer to the
  1091. documentation for that module for information on the formatter
  1092. interface.
  1093.  
  1094. The following is a summary of the interface defined by
  1095. `sgmllib.SGMLParser':
  1096.  
  1097.    * The interface to feed data to an instance is through the `feed()'
  1098.      method, which takes a string argument.  This can be called with as
  1099.      little or as much text at a time as desired; `p.feed(a);
  1100.      p.feed(b)' has the same effect as `p.feed(a+b)'.  When the data
  1101.      contains complete HTML tags, these are processed immediately;
  1102.      incomplete elements are saved in a buffer.  To force processing of
  1103.      all unprocessed data, call the `close()' method.
  1104.  
  1105.      For example, to parse the entire contents of a file, use:
  1106.           parser.feed(open('myfile.html').read())
  1107.           parser.close()
  1108.  
  1109.    * The interface to define semantics for HTML tags is very simple:
  1110.      derive a class and define methods called `start_TAG()',
  1111.      `end_TAG()', or `do_TAG()'.  The parser will call these at
  1112.      appropriate moments: `start_TAG' or `do_TAG' is called when an
  1113.      opening tag of the form `<TAG ...>' is encountered; `end_TAG' is
  1114.      called when a closing tag of the form `<TAG>' is encountered.  If
  1115.      an opening tag requires a corresponding closing tag, like `<H1>'
  1116.      ... `</H1>', the class should define the `start_TAG' method; if a
  1117.      tag requires no closing tag, like `<P>', the class should define
  1118.      the `do_TAG' method.
  1119.  
  1120. The module defines a single class:
  1121.  
  1122.  - function of module htmllib: HTMLParser (FORMATTER)
  1123.      This is the basic HTML parser class.  It supports all entity names
  1124.      required by the HTML 2.0 specification (RFC 1866).  It also defines
  1125.      handlers for all HTML 2.0 and many HTML 3.0 and 3.2 elements.
  1126.  
  1127. In addition to tag methods, the `HTMLParser' class provides some
  1128. additional methods and instance variables for use within tag methods.
  1129.  
  1130.  - data of HTMLParser method: formatter
  1131.      This is the formatter instance associated with the parser.
  1132.  
  1133.  - data of HTMLParser method: nofill
  1134.      Boolean flag which should be true when whitespace should not be
  1135.      collapsed, or false when it should be.  In general, this should
  1136.      only be true when character data is to be treated as
  1137.      "preformatted" text, as within a `<PRE>' element.  The default
  1138.      value is false.  This affects the operation of `handle_data()' and
  1139.      `save_end()'.
  1140.  
  1141.  - Method on HTMLParser: anchor_bgn (HREF, NAME, TYPE)
  1142.      This method is called at the start of an anchor region.  The
  1143.      arguments correspond to the attributes of the `<A>' tag with the
  1144.      same names.  The default implementation maintains a list of
  1145.      hyperlinks (defined by the `href' argument) within the document.
  1146.      The list of hyperlinks is available as the data attribute
  1147.      `anchorlist'.
  1148.  
  1149.  - Method on HTMLParser: anchor_end ()
  1150.      This method is called at the end of an anchor region.  The default
  1151.      implementation adds a textual footnote marker using an index into
  1152.      the list of hyperlinks created by `anchor_bgn()'.
  1153.  
  1154.  - Method on HTMLParser: handle_image (SOURCE, ALT[, ISMAP[, ALIGN[,
  1155.           WIDTH[, HEIGHT]]]])
  1156.      This method is called to handle images.  The default implementation
  1157.      simply passes the `alt' value to the `handle_data()' method.
  1158.  
  1159.  - Method on HTMLParser: save_bgn ()
  1160.      Begins saving character data in a buffer instead of sending it to
  1161.      the formatter object.  Retrieve the stored data via `save_end()'
  1162.      Use of the `save_bgn()' / `save_end()' pair may not be nested.
  1163.  
  1164.  - Method on HTMLParser: save_end ()
  1165.      Ends buffering character data and returns all data saved since the
  1166.      preceeding call to `save_bgn()'.  If `nofill' flag is false,
  1167.      whitespace is collapsed to single spaces.  A call to this method
  1168.      without a preceeding call to `save_bgn()' will raise a `TypeError'
  1169.      exception.
  1170.  
  1171.