home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !ibrowse / files / pylibi-7 < prev    next >
Encoding:
GNU Info File  |  1996-11-14  |  50.3 KB  |  1,180 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: formatter,  Next: rfc822,  Prev: htmllib,  Up: Internet and WWW
  40.  
  41. Standard Module `formatter'
  42. ===========================
  43.  
  44. This module supports two interface definitions, each with mulitple
  45. implementations.  The *formatter* interface is used by the `HTMLParser'
  46. class of the `htmllib' module, and the *writer* interface is required
  47. by the formatter interface.
  48.  
  49. Formatter objects transform an abstract flow of formatting events into
  50. specific output events on writer objects.  Formatters manage several
  51. stack structures to allow various properties of a writer object to be
  52. changed and restored; writers need not be able to handle relative
  53. changes nor any sort of "change back" operation.  Specific writer
  54. properties which may be controlled via formatter objects are horizontal
  55. alignment, font, and left margin indentations.  A mechanism is provided
  56. which supports providing arbitrary, non-exclusive style settings to a
  57. writer as well.  Additional interfaces facilitate formatting events
  58. which are not reversible, such as paragraph separation.
  59.  
  60. Writer objects encapsulate device interfaces.  Abstract devices, such
  61. as file formats, are supported as well as physical devices.  The
  62. provided implementations all work with abstract devices.  The interface
  63. makes available mechanisms for setting the properties which formatter
  64. objects manage and inserting data into the output.
  65.  
  66. * Menu:
  67.  
  68. * The Formatter Interface::
  69. * Formatter Implementations::
  70. * The Writer Interface::
  71. * Writer Implementations::
  72.  
  73. 
  74. File: pylibi,  Node: The Formatter Interface,  Next: Formatter Implementations,  Prev: formatter,  Up: formatter
  75.  
  76. The Formatter Interface
  77. -----------------------
  78.  
  79. Interfaces to create formatters are dependent on the specific formatter
  80. class being instantiated.  The interfaces described below are the
  81. required interfaces which all formatters must support once initialized.
  82.  
  83. One data element is defined at the module level:
  84.  
  85.  - data of module formatter: AS_IS
  86.      Value which can be used in the font specification passed to the
  87.      `push_font()' method described below, or as the new value to any
  88.      other `push_PROPERTY()' method.  Pushing the `AS_IS' value allows
  89.      the corresponding `pop_PROPERTY()' method to be called without
  90.      having to track whether the property was changed.
  91.  
  92. The following attributes are defined for formatter instance objects:
  93.  
  94.  - data of formatter object data: writer
  95.      The writer instance with which the formatter interacts.
  96.  
  97.  - Method on formatter object: end_paragraph (BLANKLINES)
  98.      Close any open paragraphs and insert at least `blanklines' before
  99.      the next paragraph.
  100.  
  101.  - Method on formatter object: add_line_break ()
  102.      Add a hard line break if one does not already exist.  This does not
  103.      break the logical paragraph.
  104.  
  105.  - Method on formatter object: add_hor_rule (*ARGS, **KW)
  106.      Insert a horizontal rule in the output.  A hard break is inserted
  107.      if there is data in the current paragraph, but the logical
  108.      paragraph is not broken.  The arguments and keywords are passed on
  109.      to the writer's `send_line_break()' method.
  110.  
  111.  - Method on formatter object: add_flowing_data (DATA)
  112.      Provide data which should be formatted with collapsed whitespaces.
  113.      Whitespace from preceeding and successive calls to
  114.      `add_flowing_data()' is considered as well when the whitespace
  115.      collapse is performed.  The data which is passed to this method is
  116.      expected to be word-wrapped by the output device.  Note that any
  117.      word-wrapping still must be performed by the writer object due to
  118.      the need to rely on device and font information.
  119.  
  120.  - Method on formatter object: add_literal_data (DATA)
  121.      Provide data which should be passed to the writer unchanged.
  122.      Whitespace, including newline and tab characters, are considered
  123.      legal in the value of `data'.
  124.  
  125.  - Method on formatter object: add_label_data (FORMAT, COUNTER)
  126.      Insert a label which should be placed to the left of the current
  127.      left margin.  This should be used for constructing bulleted or
  128.      numbered lists.  If the `format' value is a string, it is
  129.      interpreted as a format specification for `counter', which should
  130.      be an integer.  The result of this formatting becomes the value of
  131.      the label; if `format' is not a string it is used as the label
  132.      value directly.  The label value is passed as the only argument to
  133.      the writer's `send_label_data()' method.  Interpretation of
  134.      non-string label values is dependent on the associated writer.
  135.  
  136.      Format specifications are strings which, in combination with a
  137.      counter value, are used to compute label values.  Each character
  138.      in the format string is copied to the label value, with some
  139.      characters recognized to indicate a transform on the counter
  140.      value.  Specifically, the character "`1'" represents the counter
  141.      value formatter as an arabic number, the characters "`A'" and
  142.      "`a'" represent alphabetic representations of the counter value in
  143.      upper and lower case, respectively, and "`I'" and "`i'" represent
  144.      the counter value in Roman numerals, in upper and lower case.
  145.      Note that the alphabetic and roman transforms require that the
  146.      counter value be greater than zero.
  147.  
  148.  - Method on formatter object: flush_softspace ()
  149.      Send any pending whitespace buffered from a previous call to
  150.      `add_flowing_data()' to the associated writer object.  This should
  151.      be called before any direct manipulation of the writer object.
  152.  
  153.  - Method on formatter object: push_alignment (ALIGN)
  154.      Push a new alignment setting onto the alignment stack.  This may be
  155.      `AS_IS' if no change is desired.  If the alignment value is
  156.      changed from the previous setting, the writer's `new_alignment()'
  157.      method is called with the `align' value.
  158.  
  159.  - Method on formatter object: pop_alignment ()
  160.      Restore the previous alignment.
  161.  
  162.  - Method on formatter object: push_font ((SIZE, ITALIC, BOLD,
  163.           TELETYPE))
  164.      Change some or all font properties of the writer object.
  165.      Properties which are not set to `AS_IS' are set to the values
  166.      passed in while others are maintained at their current settings.
  167.      The writer's `new_font()' method is called with the fully resolved
  168.      font specification.
  169.  
  170.  - Method on formatter object: pop_font ()
  171.      Restore the previous font.
  172.  
  173.  - Method on formatter object: push_margin (MARGIN)
  174.      Increase the number of left margin indentations by one, associating
  175.      the logical tag `margin' with the new indentation.  The initial
  176.      margin level is `0'.  Changed values of the logical tag must be
  177.      true values; false values other than `AS_IS' are not sufficient to
  178.      change the margin.
  179.  
  180.  - Method on formatter object: pop_margin ()
  181.      Restore the previous margin.
  182.  
  183.  - Method on formatter object: push_style (*STYLES)
  184.      Push any number of arbitrary style specifications.  All styles are
  185.      pushed onto the styles stack in order.  A tuple representing the
  186.      entire stack, including `AS_IS' values, is passed to the writer's
  187.      `new_styles()' method.
  188.  
  189.  - Method on formatter object: pop_style ([N` = 1'])
  190.      Pop the last `n' style specifications passed to `push_style()'.  A
  191.      tuple representing the revised stack, including `AS_IS' values, is
  192.      passed to the writer's `new_styles()' method.
  193.  
  194.  - Method on formatter object: set_spacing (SPACING)
  195.      Set the spacing style for the writer.
  196.  
  197.  - Method on formatter object: assert_line_data ([FLAG` = 1'])
  198.      Inform the formatter that data has been added to the current
  199.      paragraph out-of-band.  This should be used when the writer has
  200.      been manipulated directly.  The optional `flag' argument can be
  201.      set to false if the writer manipulations produced a hard line
  202.      break at the end of the output.
  203.  
  204. 
  205. File: pylibi,  Node: Formatter Implementations,  Next: The Writer Interface,  Prev: The Formatter Interface,  Up: formatter
  206.  
  207. Formatter Implementations
  208. -------------------------
  209.  
  210. Two implementations of formatter objects are provided by this module.
  211. Most applications may use one of these classes without modification or
  212. subclassing.
  213.  
  214.  - function of module formatter: NullFormatter ([WRITER` = None'])
  215.      A formatter which does nothing.  If `writer' is omitted, a
  216.      `NullWriter' instance is created.  No methods of the writer are
  217.      called by `NullWriter' instances.  Implementations should inherit
  218.      from this class if implementing a writer interface but don't need
  219.      to inherit any implementation.
  220.  
  221.  - function of module formatter: AbstractFormatter (WRITER)
  222.      The standard formatter.  This implementation has demonstrated wide
  223.      applicability to many writers, and may be used directly in most
  224.      circumstances.  It has been used to implement a full-featured
  225.      world-wide web browser.
  226.  
  227. 
  228. File: pylibi,  Node: The Writer Interface,  Next: Writer Implementations,  Prev: Formatter Implementations,  Up: formatter
  229.  
  230. The Writer Interface
  231. --------------------
  232.  
  233. Interfaces to create writers are dependent on the specific writer class
  234. being instantiated.  The interfaces described below are the required
  235. interfaces which all writers must support once initialized.  Note that
  236. while most applications can use the `AbstractFormatter' class as a
  237. formatter, the writer must typically be provided by the application.
  238.  
  239.  - Method on writer object: new_alignment (ALIGN)
  240.      Set the alignment style.  The `align' value can be any object, but
  241.      by convention is a string or `None', where `None' indicates that
  242.      the writer's "preferred" alignment should be used.  Conventional
  243.      `align' values are `'left'', `'center'', `'right'', and
  244.      `'justify''.
  245.  
  246.  - Method on writer object: new_font (FONT)
  247.      Set the font style.  The value of `font' will be `None',
  248.      indicating that the device's default font should be used, or a
  249.      tuple of the form (SIZE, ITALIC, BOLD, TELETYPE).  Size will be a
  250.      string indicating the size of font that should be used; specific
  251.      strings and their interpretation must be defined by the
  252.      application.  The ITALIC, BOLD, and TELETYPE values are boolean
  253.      indicators specifying which of those font attributes should be
  254.      used.
  255.  
  256.  - Method on writer object: new_margin (MARGIN, LEVEL)
  257.      Set the margin level to the integer `level' and the logical tag to
  258.      `margin'.  Interpretation of the logical tag is at the writer's
  259.      discretion; the only restriction on the value of the logical tag
  260.      is that it not be a false value for non-zero values of `level'.
  261.  
  262.  - Method on writer object: new_spacing (SPACING)
  263.      Set the spacing style to `spacing'.
  264.  
  265.  - Method on writer object: new_styles (STYLES)
  266.      Set additional styles.  The `styles' value is a tuple of arbitrary
  267.      values; the value `AS_IS' should be ignored.  The `styles' tuple
  268.      may be interpreted either as a set or as a stack depending on the
  269.      requirements of the application and writer implementation.
  270.  
  271.  - Method on writer object: send_line_break ()
  272.      Break the current line.
  273.  
  274.  - Method on writer object: send_paragraph (BLANKLINE)
  275.      Produce a paragraph separation of at least `blankline' blank
  276.      lines, or the equivelent.  The `blankline' value will be an
  277.      integer.
  278.  
  279.  - Method on writer object: send_hor_rule (*ARGS, **KW)
  280.      Display a horizontal rule on the output device.  The arguments to
  281.      this method are entirely application- and writer-specific, and
  282.      should be interpreted with care.  The method implementation may
  283.      assume that a line break has already been issued via
  284.      `send_line_break()'.
  285.  
  286.  - Method on writer object: send_flowing_data (DATA)
  287.      Output character data which may be word-wrapped and re-flowed as
  288.      needed.  Within any sequence of calls to this method, the writer
  289.      may assume that spans of multiple whitespace characters have been
  290.      collapsed to single space characters.
  291.  
  292.  - Method on writer object: send_literal_data (DATA)
  293.      Output character data which has already been formatted for
  294.      display.  Generally, this should be interpreted to mean that line
  295.      breaks indicated by newline characters should be preserved and no
  296.      new line breaks should be introduced.  The data may contain
  297.      embedded newline and tab characters, unlike data provided to the
  298.      `send_formatted_data()' interface.
  299.  
  300.  - Method on writer object: send_label_data (DATA)
  301.      Set `data' to the left of the current left margin, if possible.
  302.      The value of `data' is not restricted; treatment of non-string
  303.      values is entirely application- and writer-dependent.  This method
  304.      will only be called at the beginning of a line.
  305.  
  306. 
  307. File: pylibi,  Node: Writer Implementations,  Prev: The Writer Interface,  Up: formatter
  308.  
  309. Writer Implementations
  310. ----------------------
  311.  
  312. Three implementations of the writer object interface are provided as
  313. examples by this module.  Most applications will need to derive new
  314. writer classes from the `NullWriter' class.
  315.  
  316.  - function of module formatter: NullWriter ()
  317.      A writer which only provides the interface definition; no actions
  318.      are taken on any methods.  This should be the base class for all
  319.      writers which do not need to inherit any implementation methods.
  320.  
  321.  - function of module formatter: AbstractWriter ()
  322.      A writer which can be used in debugging formatters, but not much
  323.      else.  Each method simply accounces itself by printing its name and
  324.      arguments on standard output.
  325.  
  326.  - function of module formatter: DumbWriter ([FILE` = None'[, MAXCOL` =
  327.           72']])
  328.      Simple writer class which writes output on the file object passed
  329.      in as `file' or, if `file' is omitted, on standard output.  The
  330.      output is simply word-wrapped to the number of columns specified by
  331.      `maxcol'.  This class is suitable for reflowing a sequence of
  332.      paragraphs.
  333.  
  334. 
  335. File: pylibi,  Node: rfc822,  Next: mimetools,  Prev: formatter,  Up: Internet and WWW
  336.  
  337. Standard Module `rfc822'
  338. ========================
  339.  
  340. This module defines a class, `Message', which represents a collection
  341. of "email headers" as defined by the Internet standard RFC 822.  It is
  342. used in various contexts, usually to read such headers from a file.
  343.  
  344. A `Message' instance is instantiated with an open file object as
  345. parameter.  Instantiation reads headers from the file up to a blank
  346. line and stores them in the instance; after instantiation, the file is
  347. positioned directly after the blank line that terminates the headers.
  348.  
  349. Input lines as read from the file may either be terminated by CR-LF or
  350. by a single linefeed; a terminating CR-LF is replaced by a single
  351. linefeed before the line is stored.
  352.  
  353. All header matching is done independent of upper or lower case; e.g.
  354. `m['From']', `m['from']' and `m['FROM']' all yield the same result.
  355.  
  356. * Menu:
  357.  
  358. * Message Objects::
  359.  
  360. 
  361. File: pylibi,  Node: Message Objects,  Prev: rfc822,  Up: rfc822
  362.  
  363. Message Objects
  364. ---------------
  365.  
  366. A `Message' instance has the following methods:
  367.  
  368.  - function of module rfc822: rewindbody ()
  369.      Seek to the start of the message body.  This only works if the file
  370.      object is seekable.
  371.  
  372.  - function of module rfc822: getallmatchingheaders (NAME)
  373.      Return a list of lines consisting of all headers matching NAME, if
  374.      any.  Each physical line, whether it is a continuation line or
  375.      not, is a separate list item.  Return the empty list if no header
  376.      matches NAME.
  377.  
  378.  - function of module rfc822: getfirstmatchingheader (NAME)
  379.      Return a list of lines comprising the first header matching NAME,
  380.      and its continuation line(s), if any.  Return `None' if there is
  381.      no header matching NAME.
  382.  
  383.  - function of module rfc822: getrawheader (NAME)
  384.      Return a single string consisting of the text after the colon in
  385.      the first header matching NAME.  This includes leading whitespace,
  386.      the trailing linefeed, and internal linefeeds and whitespace if
  387.      there any continuation line(s) were present.  Return `None' if
  388.      there is no header matching NAME.
  389.  
  390.  - function of module rfc822: getheader (NAME)
  391.      Like `getrawheader(NAME)', but strip leading and trailing
  392.      whitespace (but not internal whitespace).
  393.  
  394.  - function of module rfc822: getaddr (NAME)
  395.      Return a pair (full name, email address) parsed from the string
  396.      returned by `getheader(NAME)'.  If no header matching NAME exists,
  397.      return `None, None'; otherwise both the full name and the address
  398.      are (possibly empty )strings.
  399.  
  400.      Example: If `m''s first `From' header contains the string
  401.      `'jack@cwi.nl (Jack Jansen)'', then `m.getaddr('From')' will yield
  402.      the pair `('Jack Jansen', 'jack@cwi.nl')'.  If the header contained
  403.      `'Jack Jansen <jack@cwi.nl>'' instead, it would yield the exact
  404.      same result.
  405.  
  406.  - function of module rfc822: getaddrlist (NAME)
  407.      This is similar to `getaddr(LIST)', but parses a header containing
  408.      a list of email addresses (e.g. a `To' header) and returns a list
  409.      of (full name, email address) pairs (even if there was only one
  410.      address in the header).  If there is no header matching NAME,
  411.      return an empty list.
  412.  
  413.      XXX The current version of this function is not really correct.  It
  414.      yields bogus results if a full name contains a comma.
  415.  
  416.  - function of module rfc822: getdate (NAME)
  417.      Retrieve a header using `getheader' and parse it into a 9-tuple
  418.      compatible with `time.mktime()'.  If there is no header matching
  419.      NAME, or it is unparsable, return `None'.
  420.  
  421.      Date parsing appears to be a black art, and not all mailers adhere
  422.      to the standard.  While it has been tested and found correct on a
  423.      large collection of email from many sources, it is still possible
  424.      that this function may occasionally yield an incorrect result.
  425.  
  426. `Message' instances also support a read-only mapping interface.  In
  427. particular: `m[name]' is the same as `m.getheader(name)'; and `len(m)',
  428. `m.has_key(name)', `m.keys()', `m.values()' and `m.items()' act as
  429. expected (and consistently).
  430.  
  431. Finally, `Message' instances have two public instance variables:
  432.  
  433.  - data of module rfc822: headers
  434.      A list containing the entire set of header lines, in the order in
  435.      which they were read.  Each line contains a trailing newline.  The
  436.      blank line terminating the headers is not contained in the list.
  437.  
  438.  - data of module rfc822: fp
  439.      The file object passed at instantiation time.
  440.  
  441. 
  442. File: pylibi,  Node: mimetools,  Next: binhex,  Prev: rfc822,  Up: Internet and WWW
  443.  
  444. Standard Module `mimetools'
  445. ===========================
  446.  
  447. This module defines a subclass of the class `rfc822.Message' and a
  448. number of utility functions that are useful for the manipulation for
  449. MIME style multipart or encoded message.
  450.  
  451. It defines the following items:
  452.  
  453.  - function of module mimetools: Message (FP)
  454.      Return a new instance of the `mimetools.Message' class.  This is a
  455.      subclass of the `rfc822.Message' class, with some additional
  456.      methods (see below).
  457.  
  458.  - function of module mimetools: choose_boundary ()
  459.      Return a unique string that has a high likelihood of being usable
  460.      as a part boundary.  The string has the form
  461.      `"HOSTIPADDR.UID.PID.TIMESTAMP.RANDOM"'.
  462.  
  463.  - function of module mimetools: decode (INPUT, OUTPUT, ENCODING)
  464.      Read data encoded using the allowed MIME ENCODING from open file
  465.      object INPUT and write the decoded data to open file object
  466.      OUTPUT.  Valid values for ENCODING include `"base64"',
  467.      `"quoted-printable"' and `"uuencode"'.
  468.  
  469.  - function of module mimetools: encode (INPUT, OUTPUT, ENCODING)
  470.      Read data from open file object INPUT and write it encoded using
  471.      the allowed MIME ENCODING to open file object OUTPUT.  Valid
  472.      values for ENCODING are the same as for `decode()'.
  473.  
  474.  - function of module mimetools: copyliteral (INPUT, OUTPUT)
  475.      Read lines until EOF from open file INPUT and write them to open
  476.      file OUTPUT.
  477.  
  478.  - function of module mimetools: copybinary (INPUT, OUTPUT)
  479.      Read blocks until EOF from open file INPUT and write them to open
  480.      file OUTPUT.  The block size is currently fixed at 8192.
  481.  
  482. * Menu:
  483.  
  484. * mimetools.Message Methods::
  485.  
  486. 
  487. File: pylibi,  Node: mimetools.Message Methods,  Prev: mimetools,  Up: mimetools
  488.  
  489. Additional Methods of Message objects
  490. -------------------------------------
  491.  
  492. The `mimetools.Message' class defines the following methods in addition
  493. to the `rfc822.Message' class:
  494.  
  495.  - Method on mimetool.Message: getplist ()
  496.      Return the parameter list of the `Content-type' header.  This is a
  497.      list if strings.  For parameters of the form `KEY=VALUE', KEY is
  498.      converted to lower case but VALUE is not.  For example, if the
  499.      message contains the header `Content-type: text/html; spam=1;
  500.      Spam=2; Spam' then `getplist()' will return the Python list
  501.      `['spam=1', 'spam=2', 'Spam']'.
  502.  
  503.  - Method on mimetool.Message: getparam (NAME)
  504.      Return the VALUE of the first parameter (as returned by
  505.      `getplist()' of the form `NAME=VALUE' for the given NAME.  If
  506.      VALUE is surrounded by quotes of the form <...> or "...", these
  507.      are removed.
  508.  
  509.  - Method on mimetool.Message: getencoding ()
  510.      Return the encoding specified in the `Content-transfer-encoding'
  511.      message header.  If no such header exists, return `"7bit"'.  The
  512.      encoding is converted to lower case.
  513.  
  514.  - Method on mimetool.Message: gettype ()
  515.      Return the message type (of the form `TYPE/varsubtype') as
  516.      specified in the `Content-type' header.  If no such header exists,
  517.      return `"text/plain"'.  The type is converted to lower case.
  518.  
  519.  - Method on mimetool.Message: getmaintype ()
  520.      Return the main type as specified in the `Content-type' header.
  521.      If no such header exists, return `"text"'.  The main type is
  522.      converted to lower case.
  523.  
  524.  - Method on mimetool.Message: getsubtype ()
  525.      Return the subtype as specified in the `Content-type' header.  If
  526.      no such header exists, return `"plain"'.  The subtype is converted
  527.      to lower case.
  528.  
  529. 
  530. File: pylibi,  Node: binhex,  Next: uu,  Prev: mimetools,  Up: Internet and WWW
  531.  
  532. Standard module `binhex'
  533. ========================
  534.  
  535. This module encodes and decodes files in binhex4 format, a format
  536. allowing representation of Macintosh files in ASCII. On the macintosh,
  537. both forks of a file and the finder information are encoded (or
  538. decoded), on other platforms only the data fork is handled.
  539.  
  540. The `binhex' module defines the following functions:
  541.  
  542.  - function of module binhex: binhex (INPUT, OUTPUT)
  543.      Convert a binary file with filename INPUT to binhex file OUTPUT.
  544.      The OUTPUT parameter can either be a filename or a file-like
  545.      object (any object supporting a WRITE and CLOSE method).
  546.  
  547.  - function of module binhex: hexbin (INPUT[, OUTPUT])
  548.      Decode a binhex file INPUT. INPUT may be a filename or a file-like
  549.      object supporting READ and CLOSE methods.  The resulting file is
  550.      written to a file named OUTPUT, unless the argument is empty in
  551.      which case the output filename is read from the binhex file.
  552.  
  553. * Menu:
  554.  
  555. * notes::
  556.  
  557. 
  558. File: pylibi,  Node: notes,  Prev: binhex,  Up: binhex
  559.  
  560. notes
  561. -----
  562.  
  563. There is an alternative, more powerful interface to the coder and
  564. decoder, see the source for details.
  565.  
  566. If you code or decode textfiles on non-Macintosh platforms they will
  567. still use the macintosh newline convention (carriage-return as end of
  568. line).
  569.  
  570. As of this writing, HEXBIN appears to not work in all cases.
  571.  
  572. 
  573. File: pylibi,  Node: uu,  Next: binascii,  Prev: binhex,  Up: Internet and WWW
  574.  
  575. Standard module `uu'
  576. ====================
  577.  
  578. This module encodes and decodes files in uuencode format, allowing
  579. arbitrary binary data to be transferred over ascii-only connections.
  580. Whereever a file argument is expected, the methods accept either a
  581. pathname (`'-'' for stdin/stdout) or a file-like object.
  582.  
  583. Normally you would pass filenames, but there is one case where you have
  584. to open the file yourself: if you are on a non-unix platform and your
  585. binary file is actually a textfile that you want encoded
  586. unix-compatible you will have to open the file yourself as a textfile,
  587. so newline conversion is performed.
  588.  
  589. This code was contributed by Lance Ellinghouse, and modified by Jack
  590. Jansen.
  591.  
  592. The `uu' module defines the following functions:
  593.  
  594.  - function of module uu: encode (IN_FILE, OUT_FILE[, NAME, MODE])
  595.      Uuencode file IN_FILE into file OUT_FILE.  The uuencoded file will
  596.      have the header specifying NAME and MODE as the defaults for the
  597.      results of decoding the file. The default defaults are taken from
  598.      IN_FILE, or `'-'' and `0666' respectively.
  599.  
  600.  - function of module uu: decode (IN_FILE[, OUT_FILE, MODE])
  601.      This call decodes uuencoded file IN_FILE placing the result on
  602.      file OUT_FILE. If OUT_FILE is a pathname the MODE is also set.
  603.      Defaults for OUT_FILE and MODE are taken from the uuencode header.
  604.  
  605. 
  606. File: pylibi,  Node: binascii,  Next: xdrlib,  Prev: uu,  Up: Internet and WWW
  607.  
  608. Built-in Module `binascii'
  609. ==========================
  610.  
  611. The binascii module contains a number of methods to convert between
  612. binary and various ascii-encoded binary representations. Normally, you
  613. will not use these modules directly but use wrapper modules like UU or
  614. HEXBIN in stead, this module solely exists because bit-manipuation of
  615. large amounts of data is slow in python.
  616.  
  617. The `binascii' module defines the following functions:
  618.  
  619.  - function of module binascii: a2b_uu (STRING)
  620.      Convert a single line of uuencoded data back to binary and return
  621.      the binary data. Lines normally contain 45 (binary) bytes, except
  622.      for the last line. Line data may be followed by whitespace.
  623.  
  624.  - function of module binascii: b2a_uu (DATA)
  625.      Convert binary data to a line of ascii characters, the return
  626.      value is the converted line, including a newline char. The length
  627.      of DATA should be at most 45.
  628.  
  629.  - function of module binascii: a2b_base64 (STRING)
  630.      Convert a block of base64 data back to binary and return the
  631.      binary data. More than one line may be passed at a time.
  632.  
  633.  - function of module binascii: b2a_base64 (DATA)
  634.      Convert binary data to a line of ascii characters in base64 coding.
  635.      The return value is the converted line, including a newline char.
  636.      The length of DATA should be at most 57 to adhere to the base64
  637.      standard.
  638.  
  639.  - function of module binascii: a2b_hqx (STRING)
  640.      Convert binhex4 formatted ascii data to binary, without doing
  641.      rle-decompression. The string should contain a complete number of
  642.      binary bytes, or (in case of the last portion of the binhex4 data)
  643.      have the remaining bits zero.
  644.  
  645.  - function of module binascii: rledecode_hqx (DATA)
  646.      Perform RLE-decompression on the data, as per the binhex4
  647.      standard. The algorithm uses `0x90' after a byte as a repeat
  648.      indicator, followed by a count. A count of `0' specifies a byte
  649.      value of `0x90'. The routine returns the decompressed data, unless
  650.      data input data ends in an orphaned repeat indicator, in which
  651.      case the INCOMPLETE exception is raised.
  652.  
  653.  - function of module binascii: rlecode_hqx (DATA)
  654.      Perform binhex4 style RLE-compression on DATA and return the
  655.      result.
  656.  
  657.  - function of module binascii: b2a_hqx (DATA)
  658.      Perform hexbin4 binary-to-ascii translation and return the
  659.      resulting string. The argument should already be rle-coded, and
  660.      have a length divisible by 3 (except possibly the last fragment).
  661.  
  662.  - function of module binascii: crc_hqx (DATA, CRC)
  663.      Compute the binhex4 crc value of DATA, starting with an initial
  664.      CRC and returning the result.
  665.  
  666.  - exception of module binascii: Error
  667.      Exception raised on errors. These are usually programming errors.
  668.  
  669.  - exception of module binascii: Incomplete
  670.      Exception raised on incomplete data. These are usually not
  671.      programming errors, but handled by reading a little more data and
  672.      trying again.
  673.  
  674. 
  675. File: pylibi,  Node: xdrlib,  Prev: binascii,  Up: Internet and WWW
  676.  
  677. Standard module `xdrlib'
  678. ========================
  679.  
  680. The `xdrlib' module supports the External Data Representation Standard
  681. as described in RFC 1014, written by Sun Microsystems, Inc. June 1987.
  682. It supports most of the data types described in the RFC, although some,
  683. most notably `float' and `double' are only supported on those operating
  684. systems that provide an XDR library.
  685.  
  686. The `xdrlib' module defines two classes, one for packing variables into
  687. XDR representation, and another for unpacking from XDR representation.
  688. There are also two exception classes.
  689.  
  690. * Menu:
  691.  
  692. * Packer Objects::
  693. * Unpacker Objects::
  694. * Exceptions::
  695. * Supporting Floating Point Data::
  696.  
  697. 
  698. File: pylibi,  Node: Packer Objects,  Next: Unpacker Objects,  Prev: xdrlib,  Up: xdrlib
  699.  
  700. Packer Objects
  701. --------------
  702.  
  703. `Packer' is the class for packing data into XDR representation.  The
  704. `Packer' class is instantiated with no arguments.
  705.  
  706.  - function of module xdrlib: get_buffer ()
  707.      Returns the current pack buffer as a string.
  708.  
  709.  - function of module xdrlib: reset ()
  710.      Resets the pack buffer to the empty string.
  711.  
  712. In general, you can pack any of the most common XDR data types by
  713. calling the appropriate `pack_TYPE' method.  Each method takes a single
  714. argument, the value to pack.  The following simple data type packing
  715. methods are supported: `pack_uint', `pack_int', `pack_enum',
  716. `pack_bool', `pack_uhyper', and `pack_hyper'.
  717.  
  718. The following methods pack floating point numbers, however they require
  719. C library support.  Without the optional C built-in module, both of
  720. these methods will raise an `xdrlib.ConversionError' exception.  See
  721. the note at the end of this chapter for details.
  722.  
  723.  - function of module xdrlib: pack_float (VALUE)
  724.      Packs the single-precision floating point number VALUE.
  725.  
  726.  - function of module xdrlib: pack_double (VALUE)
  727.      Packs the double-precision floating point number VALUE.
  728.  
  729. The following methods support packing strings, bytes, and opaque data:
  730.  
  731.  - function of module xdrlib: pack_fstring (N, S)
  732.      Packs a fixed length string, S.  N is the length of the string but
  733.      it is *not* packed into the data buffer.  The string is padded
  734.      with null bytes if necessary to guaranteed 4 byte alignment.
  735.  
  736.  - function of module xdrlib: pack_fopaque (N, DATA)
  737.      Packs a fixed length opaque data stream, similarly to
  738.      `pack_fstring'.
  739.  
  740.  - function of module xdrlib: pack_string (S)
  741.      Packs a variable length string, S.  The length of the string is
  742.      first packed as an unsigned integer, then the string data is packed
  743.      with `pack_fstring'.
  744.  
  745.  - function of module xdrlib: pack_opaque (DATA)
  746.      Packs a variable length opaque data string, similarly to
  747.      `pack_string'.
  748.  
  749.  - function of module xdrlib: pack_bytes (BYTES)
  750.      Packs a variable length byte stream, similarly to `pack_string'.
  751.  
  752. The following methods support packing arrays and lists:
  753.  
  754.  - function of module xdrlib: pack_list (LIST, PACK_ITEM)
  755.      Packs a LIST of homogeneous items.  This method is useful for
  756.      lists with an indeterminate size; i.e. the size is not available
  757.      until the entire list has been walked.  For each item in the list,
  758.      an unsigned integer `1' is packed first, followed by the data value
  759.      from the list.  PACK_ITEM is the function that is called to pack
  760.      the individual item.  At the end of the list, an unsigned integer
  761.      `0' is packed.
  762.  
  763.  - function of module xdrlib: pack_farray (N, ARRAY, PACK_ITEM)
  764.      Packs a fixed length list (ARRAY) of homogeneous items.  N is the
  765.      length of the list; it is *not* packed into the buffer, but a
  766.      `ValueError' exception is raised if `len(array)' is not equal to
  767.      N.  As above, PACK_ITEM is the function used to pack each element.
  768.  
  769.  - function of module xdrlib: pack_array (LIST, PACK_ITEM)
  770.      Packs a variable length LIST of homogeneous items.  First, the
  771.      length of the list is packed as an unsigned integer, then each
  772.      element is packed as in `pack_farray' above.
  773.  
  774. 
  775. File: pylibi,  Node: Unpacker Objects,  Next: Exceptions,  Prev: Packer Objects,  Up: xdrlib
  776.  
  777. Unpacker Objects
  778. ----------------
  779.  
  780. `Unpacker' is the complementary class which unpacks XDR data values
  781. from a string buffer, and has the following methods:
  782.  
  783.  - function of module xdrlib: __init__ (DATA)
  784.      Instantiates an `Unpacker' object with the string buffer DATA.
  785.  
  786.  - function of module xdrlib: reset (DATA)
  787.      Resets the string buffer with the given DATA.
  788.  
  789.  - function of module xdrlib: get_position ()
  790.      Returns the current unpack position in the data buffer.
  791.  
  792.  - function of module xdrlib: set_position (POSITION)
  793.      Sets the data buffer unpack position to POSITION.  You should be
  794.      careful about using `get_position()' and `set_position()'.
  795.  
  796.  - function of module xdrlib: done ()
  797.      Indicates unpack completion.  Raises an `xdrlib.Error' exception
  798.      if all of the data has not been unpacked.
  799.  
  800. In addition, every data type that can be packed with a `Packer', can be
  801. unpacked with an `Unpacker'.  Unpacking methods are of the form
  802. `unpack_TYPE', and take no arguments.  They return the unpacked object.
  803. The same caveats apply for `unpack_float' and `unpack_double' as above.
  804.  
  805.  - function of module xdrlib: unpack_float ()
  806.      Unpacks a single-precision floating point number.
  807.  
  808.  - function of module xdrlib: unpack_double ()
  809.      Unpacks a double-precision floating point number, similarly to
  810.      `unpack_float'.
  811.  
  812. In addition, the following methods unpack strings, bytes, and opaque
  813. data:
  814.  
  815.  - function of module xdrlib: unpack_fstring (N)
  816.      Unpacks and returns a fixed length string.  N is the number of
  817.      characters expected.  Padding with null bytes to guaranteed 4 byte
  818.      alignment is assumed.
  819.  
  820.  - function of module xdrlib: unpack_fopaque (N)
  821.      Unpacks and returns a fixed length opaque data stream, similarly to
  822.      `unpack_fstring'.
  823.  
  824.  - function of module xdrlib: unpack_string ()
  825.      Unpacks and returns a variable length string.  The length of the
  826.      string is first unpacked as an unsigned integer, then the string
  827.      data is unpacked with `unpack_fstring'.
  828.  
  829.  - function of module xdrlib: unpack_opaque ()
  830.      Unpacks and returns a variable length opaque data string,
  831.      similarly to `unpack_string'.
  832.  
  833.  - function of module xdrlib: unpack_bytes ()
  834.      Unpacks and returns a variable length byte stream, similarly to
  835.      `unpack_string'.
  836.  
  837. The following methods support unpacking arrays and lists:
  838.  
  839.  - function of module xdrlib: unpack_list (UNPACK_ITEM)
  840.      Unpacks and returns a list of homogeneous items.  The list is
  841.      unpacked one element at a time by first unpacking an unsigned
  842.      integer flag.  If the flag is `1', then the item is unpacked and
  843.      appended to the list.  A flag of `0' indicates the end of the
  844.      list.  UNPACK_ITEM is the function that is called to unpack the
  845.      items.
  846.  
  847.  - function of module xdrlib: unpack_farray (N, UNPACK_ITEM)
  848.      Unpacks and returns (as a list) a fixed length array of homogeneous
  849.      items.  N is number of list elements to expect in the buffer.  As
  850.      above, UNPACK_ITEM is the function used to unpack each element.
  851.  
  852.  - function of module xdrlib: unpack_array (UNPACK_ITEM)
  853.      Unpacks and returns a variable length LIST of homogeneous items.
  854.      First, the length of the list is unpacked as an unsigned integer,
  855.      then each element is unpacked as in `unpack_farray' above.
  856.  
  857. 
  858. File: pylibi,  Node: Exceptions,  Next: Supporting Floating Point Data,  Prev: Unpacker Objects,  Up: xdrlib
  859.  
  860. Exceptions
  861. ----------
  862.  
  863. Exceptions in this module are coded as class instances:
  864.  
  865.  - exception of module xdrlib: Error
  866.      The base exception class.  `Error' has a single public data member
  867.      `msg' containing the description of the error.
  868.  
  869.  - exception of module xdrlib: ConversionError
  870.      Class derived from `Error'.  Contains no additional instance
  871.      variables.
  872.  
  873. Here is an example of how you would catch one of these exceptions:
  874.  
  875.      import xdrlib
  876.      p = xdrlib.Packer()
  877.      try:
  878.          p.pack_double(8.01)
  879.      except xdrlib.ConversionError, instance:
  880.          print 'packing the double failed:', instance.msg
  881.  
  882. 
  883. File: pylibi,  Node: Supporting Floating Point Data,  Prev: Exceptions,  Up: xdrlib
  884.  
  885. Supporting Floating Point Data
  886. ------------------------------
  887.  
  888. Packing and unpacking floating point data, i.e. `Packer.pack_float',
  889. `Packer.pack_double', `Unpacker.unpack_float', and
  890. `Unpacker.unpack_double', are only supported with the helper built-in
  891. `_xdr' module, which relies on your operating system having the
  892. appropriate XDR library routines.
  893.  
  894. If you have built the Python interpeter with the `_xdr' module, or have
  895. built the `_xdr' module as a shared library, `xdrlib' will use these to
  896. pack and unpack floating point numbers.  Otherwise, using these
  897. routines will raise a `ConversionError' exception.
  898.  
  899. See the Python installation instructions for details on building the
  900. `_xdr' module.
  901.  
  902. 
  903. File: pylibi,  Node: Restricted Execution,  Next: Cryptographic Services,  Prev: Internet and WWW,  Up: Top
  904.  
  905. Restricted Execution
  906. ********************
  907.  
  908. In general, Python programs have complete access to the underlying
  909. operating system throug the various functions and classes, For example,
  910. a Python program can open any file for reading and writing by using the
  911. `open()' built-in function (provided the underlying OS gives you
  912. permission!).  This is exactly what you want for most applications.
  913.  
  914. There exists a class of applications for which this "openness" is
  915. inappropriate.  Take Grail: a web browser that accepts "applets",
  916. snippets of Python code, from anywhere on the Internet for execution on
  917. the local system.  This can be used to improve the user interface of
  918. forms, for instance.  Since the originator of the code is unknown, it
  919. is obvious that it cannot be trusted with the full resources of the
  920. local machine.
  921.  
  922. *Restricted execution* is the basic framework in Python that allows for
  923. the segregation of trusted and untrusted code.  It is based on the
  924. notion that trusted Python code (a *supervisor*) can create a "padded
  925. cell' (or environment) with limited permissions, and run the untrusted
  926. code within this cell.  The untrusted code cannot break out of its
  927. cell, and can only interact with sensitive system resources through
  928. interfaces defined and managed by the trusted code.  The term
  929. "restricted execution" is favored over "safe-Python" since true safety
  930. is hard to define, and is determined by the way the restricted
  931. environment is created.  Note that the restricted environments can be
  932. nested, with inner cells creating subcells of lesser, but never
  933. greater, privilege.
  934.  
  935. An interesting aspect of Python's restricted execution model is that
  936. the interfaces presented to untrusted code usually have the same names
  937. as those presented to trusted code.  Therefore no special interfaces
  938. need to be learned to write code designed to run in a restricted
  939. environment.  And because the exact nature of the padded cell is
  940. determined by the supervisor, different restrictions can be imposed,
  941. depending on the application.  For example, it might be deemed "safe"
  942. for untrusted code to read any file within a specified directory, but
  943. never to write a file.  In this case, the supervisor may redefine the
  944. built-in `open()' function so that it raises an exception whenever the
  945. MODE parameter is `'w''.  It might also perform a `chroot()'-like
  946. operation on the FILENAME parameter, such that root is always relative
  947. to some safe "sandbox" area of the filesystem.  In this case, the
  948. untrusted code would still see an built-in `open()' function in its
  949. environment, with the same calling interface.  The semantics would be
  950. identical too, with `IOError's being raised when the supervisor
  951. determined that an unallowable parameter is being used.
  952.  
  953. The Python run-time determines whether a particular code block is
  954. executing in restricted execution mode based on the identity of the
  955. `__builtins__' object in its global variables: if this is (the
  956. dictionary of) the standard `__builtin__' module, the code is deemed to
  957. be unrestricted, else it is deemed to be restricted.
  958.  
  959. Python code executing in restricted mode faces a number of limitations
  960. that are designed to prevent it from escaping from the padded cell.
  961. For instance, the function object attribute `func_globals' and the
  962. class and instance object attribute `__dict__' are unavailable.
  963.  
  964. Two modules provide the framework for setting up restricted execution
  965. environments:
  966.  
  967. rexec
  968.      -- Basic restricted execution framework.
  969.  
  970. Bastion
  971.      -- Providing restricted access to objects.
  972.  
  973. * Menu:
  974.  
  975. * rexec::
  976. * Bastion::
  977.  
  978. 
  979. File: pylibi,  Node: rexec,  Next: Bastion,  Prev: Restricted Execution,  Up: Restricted Execution
  980.  
  981. Standard Module `rexec'
  982. =======================
  983.  
  984. This module contains the `RExec' class, which supports `r_exec()',
  985. `r_eval()', `r_execfile()', and `r_import()' methods, which are
  986. restricted versions of the standard Python functions `exec()',
  987. `eval()', `execfile()', and the `import' statement.  Code executed in
  988. this restricted environment will only have access to modules and
  989. functions that are deemed safe; you can subclass `RExec' to add or
  990. remove capabilities as desired.
  991.  
  992. *Note:* The `RExec' class can prevent code from performing unsafe
  993. operations like reading or writing disk files, or using TCP/IP sockets.
  994. However, it does not protect against code using extremely large
  995. amounts of memory or CPU time.
  996.  
  997.  - function of module rexec: RExec ([HOOKS[, VERBOSE]])
  998.      Returns an instance of the `RExec' class.
  999.  
  1000.      HOOKS is an instance of the `RHooks' class or a subclass of it.
  1001.      If it is omitted or `None', the default `RHooks' class is
  1002.      instantiated.  Whenever the RExec module searches for a module
  1003.      (even a built-in one) or reads a module's code, it doesn't
  1004.      actually go out to the file system itself.  Rather, it calls
  1005.      methods of an RHooks instance that was passed to or created by its
  1006.      constructor.  (Actually, the RExec object doesn't make these
  1007.      calls--they are made by a module loader object that's part of the
  1008.      RExec object.  This allows another level of flexibility, e.g.
  1009.      using packages.)
  1010.  
  1011.      By providing an alternate RHooks object, we can control the file
  1012.      system accesses made to import a module, without changing the
  1013.      actual algorithm that controls the order in which those accesses
  1014.      are made.  For instance, we could substitute an RHooks object that
  1015.      passes all filesystem requests to a file server elsewhere, via
  1016.      some RPC mechanism such as ILU.  Grail's applet loader uses this
  1017.      to support importing applets from a URL for a directory.
  1018.  
  1019.      If VERBOSE is true, additional debugging output may be sent to
  1020.      standard output.
  1021.  
  1022. The RExec class has the following class attributes, which are used by
  1023. the `__init__' method.  Changing them on an existing instance won't
  1024. have any effect; instead, create a subclass of `RExec' and assign them
  1025. new values in the class definition.  Instances of the new class will
  1026. then use those new values.  All these attributes are tuples of strings.
  1027.  
  1028.  - attribute of RExec object: nok_builtin_names
  1029.      Contains the names of built-in functions which will *not* be
  1030.      available to programs running in the restricted environment.  The
  1031.      value for `RExec' is `('open',' `'reload',' `'__import__')'.
  1032.      (This gives the exceptions, because by far the majority of
  1033.      built-in functions are harmless.  A subclass that wants to
  1034.      override this variable should probably start with the value from
  1035.      the base class and concatenate additional forbidden functions --
  1036.      when new dangerous built-in functions are added to Python, they
  1037.      will also be added to this module.)
  1038.  
  1039.  - attribute of RExec object: ok_builtin_modules
  1040.      Contains the names of built-in modules which can be safely
  1041.      imported.  The value for `RExec' is `('audioop',' `'array','
  1042.      `'binascii',' `'cmath',' `'errno',' `'imageop',' `'marshal','
  1043.      `'math',' `'md5',' `'operator',' `'parser',' `'regex',' `'rotor','
  1044.      `'select',' `'strop',' `'struct',' `'time')'.  A similar remark
  1045.      about overriding this variable applies -- use the value from the
  1046.      base class as a starting point.
  1047.  
  1048.  - attribute of RExec object: ok_path
  1049.      Contains the directories which will be searched when an `import'
  1050.      is performed in the restricted environment.  The value for `RExec'
  1051.      is the same as `sys.path' (at the time the module is loaded) for
  1052.      unrestricted code.
  1053.  
  1054.  - attribute of RExec object: ok_posix_names
  1055.      Contains the names of the functions in the `os' module which will
  1056.      be available to programs running in the restricted environment.
  1057.      The value for `RExec' is `('error',' `'fstat',' `'listdir','
  1058.      `'lstat',' `'readlink',' `'stat',' `'times',' `'uname','
  1059.      `'getpid',' `'getppid',' `'getcwd',' `'getuid',' `'getgid','
  1060.      `'geteuid',' `'getegid')'.
  1061.  
  1062.  - attribute of RExec object: ok_sys_names
  1063.      Contains the names of the functions and variables in the `sys'
  1064.      module which will be available to programs running in the
  1065.      restricted environment.  The value for `RExec' is `('ps1','
  1066.      `'ps2',' `'copyright',' `'version',' `'platform',' `'exit','
  1067.      `'maxint')'.
  1068.  
  1069. RExec instances support the following methods:
  1070.  
  1071.  - Method on RExec object: r_eval (CODE)
  1072.      CODE must either be a string containing a Python expression, or a
  1073.      compiled code object, which will be evaluated in the restricted
  1074.      environment's `__main__' module.  The value of the expression or
  1075.      code object will be returned.
  1076.  
  1077.  - Method on RExec object: r_exec (CODE)
  1078.      CODE must either be a string containing one or more lines of
  1079.      Python code, or a compiled code object, which will be executed in
  1080.      the restricted environment's `__main__' module.
  1081.  
  1082.  - Method on RExec object: r_execfile (FILENAME)
  1083.      Execute the Python code contained in the file FILENAME in the
  1084.      restricted environment's `__main__' module.
  1085.  
  1086. Methods whose names begin with `s_' are similar to the functions
  1087. beginning with `r_', but the code will be granted access to restricted
  1088. versions of the standard I/O streans `sys.stdin', `sys.stderr', and
  1089. `sys.stdout'.
  1090.  
  1091.  - Method on RExec object: s_eval (CODE)
  1092.      CODE must be a string containing a Python expression, which will
  1093.      be evaluated in the restricted environment.
  1094.  
  1095.  - Method on RExec object: s_exec (CODE)
  1096.      CODE must be a string containing one or more lines of Python code,
  1097.      which will be executed in the restricted environment.
  1098.  
  1099.  - Method on RExec object: s_execfile (CODE)
  1100.      Execute the Python code contained in the file FILENAME in the
  1101.      restricted environment.
  1102.  
  1103. `RExec' objects must also support various methods which will be
  1104. implicitly called by code executing in the restricted environment.
  1105. Overriding these methods in a subclass is used to change the policies
  1106. enforced by a restricted environment.
  1107.  
  1108.  - Method on RExec object: r_import (MODULENAME[, GLOBALS, LOCALS,
  1109.           FROMLIST])
  1110.      Import the module MODULENAME, raising an `ImportError' exception
  1111.      if the module is considered unsafe.
  1112.  
  1113.  - Method on RExec object: r_open (FILENAME[, MODE[, BUFSIZE]])
  1114.      Method called when `open()' is called in the restricted
  1115.      environment.  The arguments are identical to those of `open()',
  1116.      and a file object (or a class instance compatible with file
  1117.      objects) should be returned.  `RExec''s default behaviour is allow
  1118.      opening any file for reading, but forbidding any attempt to write
  1119.      a file.  See the example below for an implementation of a less
  1120.      restrictive `r_open()'.
  1121.  
  1122.  - Method on RExec object: r_reload (MODULE)
  1123.      Reload the module object MODULE, re-parsing and re-initializing it.
  1124.  
  1125.  - Method on RExec object: r_unload (MODULE)
  1126.      Unload the module object MODULE (i.e., remove it from the
  1127.      restricted environment's `sys.modules' dictionary).
  1128.  
  1129. And their equivalents with access to restricted standard I/O streams:
  1130.  
  1131.  - Method on RExec object: s_import (MODULENAME[, GLOBALS, LOCALS,
  1132.           FROMLIST])
  1133.      Import the module MODULENAME, raising an `ImportError' exception
  1134.      if the module is considered unsafe.
  1135.  
  1136.  - Method on RExec object: s_reload (MODULE)
  1137.      Reload the module object MODULE, re-parsing and re-initializing it.
  1138.  
  1139.  - Method on RExec object: s_unload (MODULE)
  1140.      Unload the module object MODULE.
  1141.  
  1142.  
  1143. * Menu:
  1144.  
  1145. * An example::
  1146.  
  1147. 
  1148. File: pylibi,  Node: An example,  Prev: rexec,  Up: rexec
  1149.  
  1150. An example
  1151. ----------
  1152.  
  1153. Let us say that we want a slightly more relaxed policy than the
  1154. standard RExec class.  For example, if we're willing to allow files in
  1155. `/tmp' to be written, we can subclass the `RExec' class:
  1156.  
  1157.      class TmpWriterRExec(rexec.RExec):
  1158.          def r_open(self, file, mode='r', buf=-1):
  1159.              if mode in ('r', 'rb'):
  1160.                  pass
  1161.              elif mode in ('w', 'wb', 'a', 'ab'):
  1162.                  # check filename : must begin with /tmp/
  1163.                  if file[:5]!='/tmp/':
  1164.                      raise IOError, "can't write outside /tmp"
  1165.                  elif (string.find(file, '/../') >= 0 or
  1166.                       file[:3] == '../' or file[-3:] == '/..'):
  1167.                      raise IOError, "'..' in filename forbidden"
  1168.              else: raise IOError, "Illegal open() mode"
  1169.              return open(file, mode, buf)
  1170. Notice that the above code will occasionally forbid a perfectly valid
  1171. filename; for example, code in the restricted environment won't be able
  1172. to open a file called `/tmp/foo/../bar'.  To fix this, the `r_open'
  1173. method would have to simplify the filename to `/tmp/bar', which would
  1174. require splitting apart the filename and performing various operations
  1175. on it.  In cases where security is at stake, it may be preferable to
  1176. write simple code which is sometimes overly restrictive, instead of
  1177. more general code that is also more complex and may harbor a subtle
  1178. security hole.
  1179.  
  1180.