home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !ibrowse / files / pylibi-5 < prev    next >
Encoding:
GNU Info File  |  1996-11-14  |  50.5 KB  |  1,320 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: Debugger Commands,  Next: How It Works,  Prev: The Python Debugger,  Up: The Python Debugger
  40.  
  41. Debugger Commands
  42. =================
  43.  
  44. The debugger recognizes the following commands.  Most commands can be
  45. abbreviated to one or two letters; e.g. "`h(elp)'" means that either
  46. "`h'" or "`help'" can be used to enter the help command (but not "`he'"
  47. or "`hel'", nor "`H'" or "`Help' or "`HELP'").  Arguments to commands
  48. must be separated by whitespace (spaces or tabs).  Optional arguments
  49. are enclosed in square brackets ("`[]'") in the command syntax; the
  50. square brackets must not be typed.  Alternatives in the command syntax
  51. are separated by a vertical bar ("`|'").
  52.  
  53. Entering a blank line repeats the last command entered.  Exception: if
  54. the last command was a "`list'" command, the next 11 lines are listed.
  55.  
  56. Commands that the debugger doesn't recognize are assumed to be Python
  57. statements and are executed in the context of the program being
  58. debugged.  Python statements can also be prefixed with an exclamation
  59. point ("`!'").  This is a powerful way to inspect the program being
  60. debugged; it is even possible to change a variable or call a function.
  61. When an exception occurs in such a statement, the exception name is
  62. printed but the debugger's state is not changed.
  63.  
  64. h(elp) [COMMAND
  65.      ]
  66.  
  67.      Without argument, print the list of available commands.  With a
  68.      COMMAND as argument, print help about that command.  "`help pdb'"
  69.      displays the full documentation file; if the environment variable
  70.      `PAGER' is defined, the file is piped through that command
  71.      instead.  Since the COMMAND argument must be an identifier, "`help
  72.      exec'" must be entered to get help on the "`!'" command.
  73.  
  74. w(here)
  75.      Print a stack trace, with the most recent frame at the bottom.  An
  76.      arrow indicates the current frame, which determines the context of
  77.      most commands.
  78.  
  79. d(own)
  80.      Move the current frame one level down in the stack trace (to an
  81.      older frame).
  82.  
  83. u(p)
  84.      Move the current frame one level up in the stack trace (to a newer
  85.      frame).
  86.  
  87. b(reak) [LINENO`|'FUNCTION
  88.      ]
  89.  
  90.      With a LINENO argument, set a break there in the current file.
  91.      With a FUNCTION argument, set a break at the entry of that
  92.      function.  Without argument, list all breaks.
  93.  
  94. cl(ear) [LINENO
  95.      ]
  96.  
  97.      With a LINENO argument, clear that break in the current file.
  98.      Without argument, clear all breaks (but first ask confirmation).
  99.  
  100. s(tep)
  101.      Execute the current line, stop at the first possible occasion
  102.      (either in a function that is called or on the next line in the
  103.      current function).
  104.  
  105. n(ext)
  106.      Continue execution until the next line in the current function is
  107.      reached or it returns.  (The difference between `next' and `step'
  108.      is that `step' stops inside a called function, while `next'
  109.      executes called functions at (nearly) full speed, only stopping at
  110.      the next line in the current function.)
  111.  
  112. r(eturn)
  113.      Continue execution until the current function returns.
  114.  
  115. c(ont(inue))
  116.      Continue execution, only stop when a breakpoint is encountered.
  117.  
  118. l(ist) [FIRST [, LAST
  119.      ]]
  120.  
  121.      List source code for the current file.  Without arguments, list 11
  122.      lines around the current line or continue the previous listing.
  123.      With one argument, list 11 lines around at that line.  With two
  124.      arguments, list the given range; if the second argument is less
  125.      than the first, it is interpreted as a count.
  126.  
  127. a(rgs)
  128.      Print the argument list of the current function.
  129.  
  130. p EXPRESSION
  131.      Evaluate the EXPRESSION in the current context and print its
  132.      value.  (Note: `print' can also be used, but is not a debugger
  133.      command -- this executes the Python `print' statement.)
  134.  
  135. [!
  136.      STATEMENT]
  137.  
  138.      Execute the (one-line) STATEMENT in the context of the current
  139.      stack frame.  The exclamation point can be omitted unless the
  140.      first word of the statement resembles a debugger command.  To set
  141.      a global variable, you can prefix the assignment command with a
  142.      "`global'" command on the same line, e.g.:
  143.           (Pdb) global list_options; list_options = ['-l']
  144.           (Pdb)
  145.  
  146. q(uit)
  147.      Quit from the debugger.  The program being executed is aborted.
  148.  
  149. 
  150. File: pylibi,  Node: How It Works,  Prev: Debugger Commands,  Up: The Python Debugger
  151.  
  152. How It Works
  153. ============
  154.  
  155. Some changes were made to the interpreter:
  156.  
  157.    * sys.settrace(func) sets the global trace function
  158.  
  159.    * there can also a local trace function (see later)
  160.  
  161. Trace functions have three arguments: (FRAME, EVENT, ARG)
  162.  
  163. FRAME
  164.      is the current stack frame
  165.  
  166. EVENT
  167.      is a string: `'call'', `'line'', `'return'' or `'exception''
  168.  
  169. ARG
  170.      is dependent on the event type
  171.  
  172. A trace function should return a new trace function or None.  Class
  173. methods are accepted (and most useful!) as trace methods.
  174.  
  175. The events have the following meaning:
  176.  
  177. `'call''
  178.      A function is called (or some other code block entered).  The
  179.      global trace function is called; arg is the argument list to the
  180.      function; the return value specifies the local trace function.
  181.  
  182. `'line''
  183.      The interpreter is about to execute a new line of code (sometimes
  184.      multiple line events on one line exist).  The local trace function
  185.      is called; arg in None; the return value specifies the new local
  186.      trace function.
  187.  
  188. `'return''
  189.      A function (or other code block) is about to return.  The local
  190.      trace function is called; arg is the value that will be returned.
  191.      The trace function's return value is ignored.
  192.  
  193. `'exception''
  194.      An exception has occurred.  The local trace function is called;
  195.      arg is a triple (exception, value, traceback); the return value
  196.      specifies the new local trace function
  197.  
  198. Note that as an exception is propagated down the chain of callers, an
  199. `'exception'' event is generated at each level.
  200.  
  201. Stack frame objects have the following read-only attributes:
  202.  
  203. f_code
  204.      the code object being executed
  205.  
  206. f_lineno
  207.      the current line number (`-1' for `'call'' events)
  208.  
  209. f_back
  210.      the stack frame of the caller, or None
  211.  
  212. f_locals
  213.      dictionary containing local name bindings
  214.  
  215. f_globals
  216.      dictionary containing global name bindings
  217.  
  218. Code objects have the following read-only attributes:
  219.  
  220. co_code
  221.      the code string
  222.  
  223. co_names
  224.      the list of names used by the code
  225.  
  226. co_consts
  227.      the list of (literal) constants used by the code
  228.  
  229. co_filename
  230.      the filename from which the code was compiled
  231.  
  232. 
  233. File: pylibi,  Node: The Python Profiler,  Next: Internet and WWW,  Prev: The Python Debugger,  Up: Top
  234.  
  235. The Python Profiler
  236. *******************
  237.  
  238. Copyright (C) 1994, by InfoSeek Corporation, all rights reserved.
  239.  
  240. Written by James Roskind(1)
  241.  
  242. Permission to use, copy, modify, and distribute this Python software
  243. and its associated documentation for any purpose (subject to the
  244. restriction in the following sentence) without fee is hereby granted,
  245. provided that the above copyright notice appears in all copies, and
  246. that both that copyright notice and this permission notice appear in
  247. supporting documentation, and that the name of InfoSeek not be used in
  248. advertising or publicity pertaining to distribution of the software
  249. without specific, written prior permission.  This permission is
  250. explicitly restricted to the copying and modification of the software
  251. to remain in Python, compiled Python, or other languages (such as C)
  252. wherein the modified or derived code is exclusively imported into a
  253. Python module.
  254.  
  255. INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
  256. SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  257. FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR ANY
  258. SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
  259. RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
  260. CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  261. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  262.  
  263. The profiler was written after only programming in Python for 3 weeks.
  264. As a result, it is probably clumsy code, but I don't know for sure yet
  265. 'cause I'm a beginner :-).  I did work hard to make the code run fast,
  266. so that profiling would be a reasonable thing to do.  I tried not to
  267. repeat code fragments, but I'm sure I did some stuff in really awkward
  268. ways at times.  Please send suggestions for improvements to:
  269. `jar@netscape.com'.  I won't promise *any* support.  ...but I'd
  270. appreciate the feedback.
  271.  
  272. * Menu:
  273.  
  274. * Profiler Introduction::
  275. * Profiler Changes::
  276. * Instant Users Manual::
  277. * Deterministic Profiling::
  278. * Reference Manual::
  279. * Limitations::
  280. * Calibration::
  281. * Profiler Extensions::
  282.  
  283. ---------- Footnotes ----------
  284.  
  285. (1) Updated and converted to LaTeX by Guido van Rossum.  The references
  286. to the old profiler are left in the text, although it no longer exists.
  287.  
  288. 
  289. File: pylibi,  Node: Profiler Introduction,  Next: Profiler Changes,  Prev: The Python Profiler,  Up: The Python Profiler
  290.  
  291. Introduction to the profiler
  292. ============================
  293.  
  294. A "profiler" is a program that describes the run time performance of a
  295. program, providing a variety of statistics.  This documentation
  296. describes the profiler functionality provided in the modules `profile'
  297. and `pstats.'  This profiler provides "deterministic profiling" of any
  298. Python programs.  It also provides a series of report generation tools
  299. to allow users to rapidly examine the results of a profile operation.
  300.  
  301. 
  302. File: pylibi,  Node: Profiler Changes,  Next: Instant Users Manual,  Prev: Profiler Introduction,  Up: The Python Profiler
  303.  
  304. How Is This Profiler Different From The Old Profiler?
  305. =====================================================
  306.  
  307. The big changes from old profiling module are that you get more
  308. information, and you pay less CPU time.  It's not a trade-off, it's a
  309. trade-up.
  310.  
  311. To be specific:
  312.  
  313. Bugs removed:
  314.      Local stack frame is no longer molested, execution time is now
  315.      charged to correct functions.
  316.  
  317. Accuracy increased:
  318.      Profiler execution time is no longer charged to user's code,
  319.      calibration for platform is supported, file reads are not done *by*
  320.      profiler *during* profiling (and charged to user's code!).
  321.  
  322. Speed increased:
  323.      Overhead CPU cost was reduced by more than a factor of two
  324.      (perhaps a factor of five), lightweight profiler module is all
  325.      that must be loaded, and the report generating module (`pstats')
  326.      is not needed during profiling.
  327.  
  328. Recursive functions support:
  329.      Cumulative times in recursive functions are correctly calculated;
  330.      recursive entries are counted.
  331.  
  332. Large growth in report generating UI:
  333.      Distinct profiles runs can be added together forming a
  334.      comprehensive report; functions that import statistics take
  335.      arbitrary lists of files; sorting criteria is now based on
  336.      keywords (instead of 4 integer options); reports shows what
  337.      functions were profiled as well as what profile file was
  338.      referenced; output format has been improved.
  339.  
  340. 
  341. File: pylibi,  Node: Instant Users Manual,  Next: Deterministic Profiling,  Prev: Profiler Changes,  Up: The Python Profiler
  342.  
  343. Instant Users Manual
  344. ====================
  345.  
  346. This section is provided for users that "don't want to read the
  347. manual." It provides a very brief overview, and allows a user to
  348. rapidly perform profiling on an existing application.
  349.  
  350. To profile an application with a main entry point of `foo()', you would
  351. add the following to your module:
  352.  
  353.          import profile
  354.          profile.run("foo()")
  355.  
  356. The above action would cause `foo()' to be run, and a series of
  357. informative lines (the profile) to be printed.  The above approach is
  358. most useful when working with the interpreter.  If you would like to
  359. save the results of a profile into a file for later examination, you
  360. can supply a file name as the second argument to the `run()' function:
  361.  
  362.          import profile
  363.          profile.run("foo()", 'fooprof')
  364.  
  365. When you wish to review the profile, you should use the methods in the
  366. `pstats' module.  Typically you would load the statistics data as
  367. follows:
  368.  
  369.          import pstats
  370.          p = pstats.Stats('fooprof')
  371.  
  372. The class `Stats' (the above code just created an instance of this
  373. class) has a variety of methods for manipulating and printing the data
  374. that was just read into `p'.  When you ran `profile.run()' above, what
  375. was printed was the result of three method calls:
  376.  
  377.          p.strip_dirs().sort_stats(-1).print_stats()
  378.  
  379. The first method removed the extraneous path from all the module names.
  380. The second method sorted all the entries according to the standard
  381. module/line/name string that is printed (this is to comply with the
  382. semantics of the old profiler).  The third method printed out all the
  383. statistics.  You might try the following sort calls:
  384.  
  385.          p.sort_stats('name')
  386.          p.print_stats()
  387.  
  388. The first call will actually sort the list by function name, and the
  389. second call will print out the statistics.  The following are some
  390. interesting calls to experiment with:
  391.  
  392.          p.sort_stats('cumulative').print_stats(10)
  393.  
  394. This sorts the profile by cumulative time in a function, and then only
  395. prints the ten most significant lines.  If you want to understand what
  396. algorithms are taking time, the above line is what you would use.
  397.  
  398. If you were looking to see what functions were looping a lot, and
  399. taking a lot of time, you would do:
  400.  
  401.          p.sort_stats('time').print_stats(10)
  402.  
  403. to sort according to time spent within each function, and then print
  404. the statistics for the top ten functions.
  405.  
  406. You might also try:
  407.  
  408.          p.sort_stats('file').print_stats('__init__')
  409.  
  410. This will sort all the statistics by file name, and then print out
  411. statistics for only the class init methods ('cause they are spelled
  412. with `__init__' in them).  As one final example, you could try:
  413.  
  414.          p.sort_stats('time', 'cum').print_stats(.5, 'init')
  415.  
  416. This line sorts statistics with a primary key of time, and a secondary
  417. key of cumulative time, and then prints out some of the statistics.  To
  418. be specific, the list is first culled down to 50% (re: `.5') of its
  419. original size, then only lines containing `init' are maintained, and
  420. that sub-sub-list is printed.
  421.  
  422. If you wondered what functions called the above functions, you could
  423. now (`p' is still sorted according to the last criteria) do:
  424.  
  425.          p.print_callers(.5, 'init')
  426.  
  427. and you would get a list of callers for each of the listed functions.
  428.  
  429. If you want more functionality, you're going to have to read the
  430. manual, or guess what the following functions do:
  431.  
  432.          p.print_callees()
  433.          p.add('fooprof')
  434.  
  435. 
  436. File: pylibi,  Node: Deterministic Profiling,  Next: Reference Manual,  Prev: Instant Users Manual,  Up: The Python Profiler
  437.  
  438. What Is Deterministic Profiling?
  439. ================================
  440.  
  441. "Deterministic profiling" is meant to reflect the fact that all
  442. "function call", "function return", and "exception" events are
  443. monitored, and precise timings are made for the intervals between these
  444. events (during which time the user's code is executing).  In contrast,
  445. "statistical profiling" (which is not done by this module) randomly
  446. samples the effective instruction pointer, and deduces where time is
  447. being spent.  The latter technique traditionally involves less overhead
  448. (as the code does not need to be instrumented), but provides only
  449. relative indications of where time is being spent.
  450.  
  451. In Python, since there is an interpreter active during execution, the
  452. presence of instrumented code is not required to do deterministic
  453. profiling.  Python automatically provides a "hook" (optional callback)
  454. for each event.  In addition, the interpreted nature of Python tends to
  455. add so much overhead to execution, that deterministic profiling tends
  456. to only add small processing overhead in typical applications.  The
  457. result is that deterministic profiling is not that expensive, yet
  458. provides extensive run time statistics about the execution of a Python
  459. program.
  460.  
  461. Call count statistics can be used to identify bugs in code (surprising
  462. counts), and to identify possible inline-expansion points (high call
  463. counts).  Internal time statistics can be used to identify "hot loops"
  464. that should be carefully optimized.  Cumulative time statistics should
  465. be used to identify high level errors in the selection of algorithms.
  466. Note that the unusual handling of cumulative times in this profiler
  467. allows statistics for recursive implementations of algorithms to be
  468. directly compared to iterative implementations.
  469.  
  470. 
  471. File: pylibi,  Node: Reference Manual,  Next: Limitations,  Prev: Deterministic Profiling,  Up: The Python Profiler
  472.  
  473. Reference Manual
  474. ================
  475.  
  476. The primary entry point for the profiler is the global function
  477. `profile.run()'.  It is typically used to create any profile
  478. information.  The reports are formatted and printed using methods of
  479. the class `pstats.Stats'.  The following is a description of all of
  480. these standard entry points and functions.  For a more in-depth view of
  481. some of the code, consider reading the later section on Profiler
  482. Extensions, which includes discussion of how to derive "better"
  483. profilers from the classes presented, or reading the source code for
  484. these modules.
  485.  
  486.  - profiler function: profile.run (STRING[, FILENAME[, ...]])
  487.      This function takes a single argument that has can be passed to the
  488.      `exec' statement, and an optional file name.  In all cases this
  489.      routine attempts to `exec' its first argument, and gather profiling
  490.      statistics from the execution. If no file name is present, then
  491.      this function automatically prints a simple profiling report,
  492.      sorted by the standard name string (file/line/function-name) that
  493.      is presented in each line.  The following is a typical output from
  494.      such a call:
  495.  
  496.                 main()
  497.                 2706 function calls (2004 primitive calls) in 4.504 CPU seconds
  498.           
  499.           Ordered by: standard name
  500.           
  501.           ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  502.                2    0.006    0.003    0.953    0.477 pobject.py:75(save_objects)
  503.             43/3    0.533    0.012    0.749    0.250 pobject.py:99(evaluate)
  504.            ...
  505.  
  506.      The first line indicates that this profile was generated by the
  507.      call:
  508.      `profile.run('main()')', and hence the exec'ed string is
  509.      `'main()''.  The second line indicates that 2706 calls were
  510.      monitored.  Of those calls, 2004 were "primitive".  We define
  511.      "primitive" to mean that the call was not induced via recursion.
  512.      The next line: `Ordered by: standard name', indicates that the
  513.      text string in the far right column was used to sort the output.
  514.      The column headings include:
  515.  
  516.     ncalls
  517.           for the number of calls,
  518.  
  519.     tottime
  520.           for the total time spent in the given function (and excluding
  521.           time made in calls to sub-functions),
  522.  
  523.     percall
  524.           is the quotient of `tottime' divided by `ncalls'
  525.  
  526.     cumtime
  527.           is the total time spent in this and all subfunctions (i.e.,
  528.           from invocation till exit). This figure is accurate *even*
  529.           for recursive functions.
  530.  
  531.     percall
  532.           is the quotient of `cumtime' divided by primitive calls
  533.  
  534.     filename:lineno(function)
  535.           provides the respective data of each function
  536.  
  537.      When there are two numbers in the first column (e.g.: `43/3'),
  538.      then the latter is the number of primitive calls, and the former is
  539.      the actual number of calls.  Note that when the function does not
  540.      recurse, these two values are the same, and only the single figure
  541.      is printed.
  542.  
  543.  
  544.  - profiler function: pstats.Stats (FILENAME[, ...])
  545.      This class constructor creates an instance of a "statistics object"
  546.      from a FILENAME (or set of filenames).  `Stats' objects are
  547.      manipulated by methods, in order to print useful reports.
  548.  
  549.      The file selected by the above constructor must have been created
  550.      by the corresponding version of `profile'.  To be specific, there
  551.      is *NO* file compatibility guaranteed with future versions of this
  552.      profiler, and there is no compatibility with files produced by
  553.      other profilers (e.g., the old system profiler).
  554.  
  555.      If several files are provided, all the statistics for identical
  556.      functions will be coalesced, so that an overall view of several
  557.      processes can be considered in a single report.  If additional
  558.      files need to be combined with data in an existing `Stats' object,
  559.      the `add()' method can be used.
  560.  
  561. * Menu:
  562.  
  563. * The Stats Class::
  564.  
  565. 
  566. File: pylibi,  Node: The Stats Class,  Prev: Reference Manual,  Up: Reference Manual
  567.  
  568. The `Stats' Class
  569. -----------------
  570.  
  571.  - Method on Stats: strip_dirs ()
  572.      This method for the `Stats' class removes all leading path
  573.      information from file names.  It is very useful in reducing the
  574.      size of the printout to fit within (close to) 80 columns.  This
  575.      method modifies the object, and the stripped information is lost.
  576.      After performing a strip operation, the object is considered to
  577.      have its entries in a "random" order, as it was just after object
  578.      initialization and loading.  If `strip_dirs()' causes two function
  579.      names to be indistinguishable (i.e., they are on the same line of
  580.      the same filename, and have the same function name), then the
  581.      statistics for these two entries are accumulated into a single
  582.      entry.
  583.  
  584.  - Method on Stats: add (FILENAME[, ...])
  585.      This method of the `Stats' class accumulates additional profiling
  586.      information into the current profiling object.  Its arguments
  587.      should refer to filenames created by the corresponding version of
  588.      `profile.run()'.  Statistics for identically named (re: file,
  589.      line, name) functions are automatically accumulated into single
  590.      function statistics.
  591.  
  592.  - Method on Stats: sort_stats (KEY[, ...])
  593.      This method modifies the `Stats' object by sorting it according to
  594.      the supplied criteria.  The argument is typically a string
  595.      identifying the basis of a sort (example: `"time"' or `"name"').
  596.  
  597.      When more than one key is provided, then additional keys are used
  598.      as secondary criteria when the there is equality in all keys
  599.      selected before them.  For example, sort_stats('name', 'file')
  600.      will sort all the entries according to their function name, and
  601.      resolve all ties (identical function names) by sorting by file
  602.      name.
  603.  
  604.      Abbreviations can be used for any key names, as long as the
  605.      abbreviation is unambiguous.  The following are the keys currently
  606.      defined:
  607.  
  608.     *Valid Arg*
  609.           --  *Meaning*
  610.  
  611.     `"calls"'
  612.           call count
  613.  
  614.     `"cumulative"'
  615.           cumulative time
  616.  
  617.     `"file"'
  618.           file name
  619.  
  620.     `"module"'
  621.           file name
  622.  
  623.     `"pcalls"'
  624.           primitive call count
  625.  
  626.     `"line"'
  627.           line number
  628.  
  629.     `"name"'
  630.           function name
  631.  
  632.     `"nfl"'
  633.           name/file/line
  634.  
  635.     `"stdname"'
  636.           standard name
  637.  
  638.     `"time"'
  639.           internal time
  640.  
  641.      Note that all sorts on statistics are in descending order (placing
  642.      most time consuming items first), where as name, file, and line
  643.      number searches are in ascending order (i.e., alphabetical). The
  644.      subtle distinction between `"nfl"' and `"stdname"' is that the
  645.      standard name is a sort of the name as printed, which means that
  646.      the embedded line numbers get compared in an odd way.  For
  647.      example, lines 3, 20, and 40 would (if the file names were the
  648.      same) appear in the string order 20, 3 and 40.  In contrast,
  649.      `"nfl"' does a numeric compare of the line numbers.  In fact,
  650.      `sort_stats("nfl")' is the same as `sort_stats("name", "file",
  651.      "line")'.
  652.  
  653.      For compatibility with the old profiler, the numeric arguments
  654.      `-1', `0', `1', and `2' are permitted.  They are interpreted as
  655.      `"stdname"', `"calls"', `"time"', and `"cumulative"' respectively.
  656.      If this old style format (numeric) is used, only one sort key
  657.      (the numeric key) will be used, and additional arguments will be
  658.      silently ignored.
  659.  
  660.  - Method on Stats: reverse_order ()
  661.      This method for the `Stats' class reverses the ordering of the
  662.      basic list within the object.  This method is provided primarily
  663.      for compatibility with the old profiler.  Its utility is
  664.      questionable now that ascending vs descending order is properly
  665.      selected based on the sort key of choice.
  666.  
  667.  - Method on Stats: print_stats (RESTRICTION[, ...])
  668.      This method for the `Stats' class prints out a report as described
  669.      in the `profile.run()' definition.
  670.  
  671.      The order of the printing is based on the last `sort_stats()'
  672.      operation done on the object (subject to caveats in `add()' and
  673.      `strip_dirs())'.
  674.  
  675.      The arguments provided (if any) can be used to limit the list down
  676.      to the significant entries.  Initially, the list is taken to be the
  677.      complete set of profiled functions.  Each restriction is either an
  678.      integer (to select a count of lines), or a decimal fraction between
  679.      0.0 and 1.0 inclusive (to select a percentage of lines), or a
  680.      regular expression (to pattern match the standard name that is
  681.      printed).  If several restrictions are provided, then they are
  682.      applied sequentially.  For example:
  683.  
  684.               print_stats(.1, "foo:")
  685.  
  686.      would first limit the printing to first 10% of list, and then only
  687.      print functions that were part of filename `.*foo:'.  In contrast,
  688.      the command:
  689.  
  690.               print_stats("foo:", .1)
  691.  
  692.      would limit the list to all functions having file names `.*foo:',
  693.      and then proceed to only print the first 10% of them.
  694.  
  695.  - Method on Stats: print_callers (RESTRICTIONS[, ...])
  696.      This method for the `Stats' class prints a list of all functions
  697.      that called each function in the profiled database.  The ordering
  698.      is identical to that provided by `print_stats()', and the
  699.      definition of the restricting argument is also identical.  For
  700.      convenience, a number is shown in parentheses after each caller to
  701.      show how many times this specific call was made.  A second
  702.      non-parenthesized number is the cumulative time spent in the
  703.      function at the right.
  704.  
  705.  - Method on Stats: print_callees (RESTRICTIONS[, ...])
  706.      This method for the `Stats' class prints a list of all function
  707.      that were called by the indicated function.  Aside from this
  708.      reversal of direction of calls (re: called vs was called by), the
  709.      arguments and ordering are identical to the `print_callers()'
  710.      method.
  711.  
  712.  - Method on Stats: ignore ()
  713.      This method of the `Stats' class is used to dispose of the value
  714.      returned by earlier methods.  All standard methods in this class
  715.      return the instance that is being processed, so that the commands
  716.      can be strung together.  For example:
  717.  
  718.           pstats.Stats('foofile').strip_dirs().sort_stats('cum') \
  719.                                  .print_stats().ignore()
  720.  
  721.      would perform all the indicated functions, but it would not return
  722.      the final reference to the `Stats' instance.(1)
  723.  
  724. ---------- Footnotes ----------
  725.  
  726. (1) This was once necessary, when Python would print any unused
  727. expression result that was not `None'.  The method is still defined for
  728. backward compatibility.
  729.  
  730. 
  731. File: pylibi,  Node: Limitations,  Next: Calibration,  Prev: Reference Manual,  Up: The Python Profiler
  732.  
  733. Limitations
  734. ===========
  735.  
  736. There are two fundamental limitations on this profiler.  The first is
  737. that it relies on the Python interpreter to dispatch "call", "return",
  738. and "exception" events.  Compiled C code does not get interpreted, and
  739. hence is "invisible" to the profiler.  All time spent in C code
  740. (including builtin functions) will be charged to the Python function
  741. that invoked the C code.  If the C code calls out to some native Python
  742. code, then those calls will be profiled properly.
  743.  
  744. The second limitation has to do with accuracy of timing information.
  745. There is a fundamental problem with deterministic profilers involving
  746. accuracy.  The most obvious restriction is that the underlying "clock"
  747. is only ticking at a rate (typically) of about .001 seconds.  Hence no
  748. measurements will be more accurate that that underlying clock.  If
  749. enough measurements are taken, then the "error" will tend to average
  750. out. Unfortunately, removing this first error induces a second source
  751. of error...
  752.  
  753. The second problem is that it "takes a while" from when an event is
  754. dispatched until the profiler's call to get the time actually *gets*
  755. the state of the clock.  Similarly, there is a certain lag when exiting
  756. the profiler event handler from the time that the clock's value was
  757. obtained (and then squirreled away), until the user's code is once
  758. again executing.  As a result, functions that are called many times, or
  759. call many functions, will typically accumulate this error.  The error
  760. that accumulates in this fashion is typically less than the accuracy of
  761. the clock (i.e., less than one clock tick), but it *can* accumulate and
  762. become very significant.  This profiler provides a means of calibrating
  763. itself for a given platform so that this error can be probabilistically
  764. (i.e., on the average) removed.  After the profiler is calibrated, it
  765. will be more accurate (in a least square sense), but it will sometimes
  766. produce negative numbers (when call counts are exceptionally low, and
  767. the gods of probability work against you :-). )  Do *NOT* be alarmed by
  768. negative numbers in the profile.  They should *only* appear if you have
  769. calibrated your profiler, and the results are actually better than
  770. without calibration.
  771.  
  772. 
  773. File: pylibi,  Node: Calibration,  Next: Profiler Extensions,  Prev: Limitations,  Up: The Python Profiler
  774.  
  775. Calibration
  776. ===========
  777.  
  778. The profiler class has a hard coded constant that is added to each
  779. event handling time to compensate for the overhead of calling the time
  780. function, and socking away the results.  The following procedure can be
  781. used to obtain this constant for a given platform (see discussion in
  782. section Limitations above).
  783.  
  784.          import profile
  785.          pr = profile.Profile()
  786.          pr.calibrate(100)
  787.          pr.calibrate(100)
  788.          pr.calibrate(100)
  789.  
  790. The argument to calibrate() is the number of times to try to do the
  791. sample calls to get the CPU times.  If your computer is *very* fast,
  792. you might have to do:
  793.  
  794.          pr.calibrate(1000)
  795.  
  796. or even:
  797.  
  798.          pr.calibrate(10000)
  799.  
  800. The object of this exercise is to get a fairly consistent result.  When
  801. you have a consistent answer, you are ready to use that number in the
  802. source code.  For a Sun Sparcstation 1000 running Solaris 2.3, the
  803. magical number is about .00053.  If you have a choice, you are better
  804. off with a smaller constant, and your results will "less often" show up
  805. as negative in profile statistics.
  806.  
  807. The following shows how the trace_dispatch() method in the Profile
  808. class should be modified to install the calibration constant on a Sun
  809. Sparcstation 1000:
  810.  
  811.          def trace_dispatch(self, frame, event, arg):
  812.              t = self.timer()
  813.              t = t[0] + t[1] - self.t - .00053 # Calibration constant
  814.      
  815.              if self.dispatch[event](frame,t):
  816.                  t = self.timer()
  817.                  self.t = t[0] + t[1]
  818.              else:
  819.                  r = self.timer()
  820.                  self.t = r[0] + r[1] - t # put back unrecorded delta
  821.              return
  822.  
  823. Note that if there is no calibration constant, then the line containing
  824. the callibration constant should simply say:
  825.  
  826.              t = t[0] + t[1] - self.t  # no calibration constant
  827.  
  828. You can also achieve the same results using a derived class (and the
  829. profiler will actually run equally fast!!), but the above method is the
  830. simplest to use.  I could have made the profiler "self calibrating",
  831. but it would have made the initialization of the profiler class slower,
  832. and would have required some *very* fancy coding, or else the use of a
  833. variable where the constant `.00053' was placed in the code shown.
  834. This is a *VERY* critical performance section, and there is no reason
  835. to use a variable lookup at this point, when a constant can be used.
  836.  
  837. 
  838. File: pylibi,  Node: Profiler Extensions,  Prev: Calibration,  Up: The Python Profiler
  839.  
  840. Extensions -- Deriving Better Profilers
  841. =======================================
  842.  
  843. The `Profile' class of module `profile' was written so that derived
  844. classes could be developed to extend the profiler.  Rather than
  845. describing all the details of such an effort, I'll just present the
  846. following two examples of derived classes that can be used to do
  847. profiling.  If the reader is an avid Python programmer, then it should
  848. be possible to use these as a model and create similar (and perchance
  849. better) profile classes.
  850.  
  851. If all you want to do is change how the timer is called, or which timer
  852. function is used, then the basic class has an option for that in the
  853. constructor for the class.  Consider passing the name of a function to
  854. call into the constructor:
  855.  
  856.          pr = profile.Profile(your_time_func)
  857.  
  858. The resulting profiler will call `your_time_func()' instead of
  859. `os.times()'.  The function should return either a single number or a
  860. list of numbers (like what `os.times()' returns).  If the function
  861. returns a single time number, or the list of returned numbers has
  862. length 2, then you will get an especially fast version of the dispatch
  863. routine.
  864.  
  865. Be warned that you *should* calibrate the profiler class for the timer
  866. function that you choose.  For most machines, a timer that returns a
  867. lone integer value will provide the best results in terms of low
  868. overhead during profiling.  (os.times is *pretty* bad, 'cause it
  869. returns a tuple of floating point values, so all arithmetic is floating
  870. point in the profiler!).  If you want to substitute a better timer in
  871. the cleanest fashion, you should derive a class, and simply put in the
  872. replacement dispatch method that better handles your timer call, along
  873. with the appropriate calibration constant :-).
  874.  
  875. * Menu:
  876.  
  877. * OldProfile Class::
  878. * HotProfile Class::
  879.  
  880. 
  881. File: pylibi,  Node: OldProfile Class,  Next: HotProfile Class,  Prev: Profiler Extensions,  Up: Profiler Extensions
  882.  
  883. OldProfile Class
  884. ----------------
  885.  
  886. The following derived profiler simulates the old style profiler,
  887. providing errant results on recursive functions. The reason for the
  888. usefulness of this profiler is that it runs faster (i.e., less
  889. overhead) than the old profiler.  It still creates all the caller
  890. stats, and is quite useful when there is *no* recursion in the user's
  891. code.  It is also a lot more accurate than the old profiler, as it does
  892. not charge all its overhead time to the user's code.
  893.  
  894.      class OldProfile(Profile):
  895.      
  896.          def trace_dispatch_exception(self, frame, t):
  897.              rt, rtt, rct, rfn, rframe, rcur = self.cur
  898.              if rcur and not rframe is frame:
  899.                  return self.trace_dispatch_return(rframe, t)
  900.              return 0
  901.      
  902.          def trace_dispatch_call(self, frame, t):
  903.              fn = `frame.f_code`
  904.      
  905.              self.cur = (t, 0, 0, fn, frame, self.cur)
  906.              if self.timings.has_key(fn):
  907.                  tt, ct, callers = self.timings[fn]
  908.                  self.timings[fn] = tt, ct, callers
  909.              else:
  910.                  self.timings[fn] = 0, 0, {}
  911.              return 1
  912.      
  913.          def trace_dispatch_return(self, frame, t):
  914.              rt, rtt, rct, rfn, frame, rcur = self.cur
  915.              rtt = rtt + t
  916.              sft = rtt + rct
  917.      
  918.              pt, ptt, pct, pfn, pframe, pcur = rcur
  919.              self.cur = pt, ptt+rt, pct+sft, pfn, pframe, pcur
  920.      
  921.              tt, ct, callers = self.timings[rfn]
  922.              if callers.has_key(pfn):
  923.                  callers[pfn] = callers[pfn] + 1
  924.              else:
  925.                  callers[pfn] = 1
  926.              self.timings[rfn] = tt+rtt, ct + sft, callers
  927.      
  928.              return 1
  929.      
  930.      
  931.          def snapshot_stats(self):
  932.              self.stats = {}
  933.              for func in self.timings.keys():
  934.                  tt, ct, callers = self.timings[func]
  935.                  nor_func = self.func_normalize(func)
  936.                  nor_callers = {}
  937.                  nc = 0
  938.                  for func_caller in callers.keys():
  939.                      nor_callers[self.func_normalize(func_caller)]=\
  940.                            callers[func_caller]
  941.                      nc = nc + callers[func_caller]
  942.                  self.stats[nor_func] = nc, nc, tt, ct, nor_callers
  943.  
  944. 
  945. File: pylibi,  Node: HotProfile Class,  Prev: OldProfile Class,  Up: Profiler Extensions
  946.  
  947. HotProfile Class
  948. ----------------
  949.  
  950. This profiler is the fastest derived profile example.  It does not
  951. calculate caller-callee relationships, and does not calculate
  952. cumulative time under a function.  It only calculates time spent in a
  953. function, so it runs very quickly (re: very low overhead).  In truth,
  954. the basic profiler is so fast, that is probably not worth the savings
  955. to give up the data, but this class still provides a nice example.
  956.  
  957.      class HotProfile(Profile):
  958.      
  959.          def trace_dispatch_exception(self, frame, t):
  960.              rt, rtt, rfn, rframe, rcur = self.cur
  961.              if rcur and not rframe is frame:
  962.                  return self.trace_dispatch_return(rframe, t)
  963.              return 0
  964.      
  965.          def trace_dispatch_call(self, frame, t):
  966.              self.cur = (t, 0, frame, self.cur)
  967.              return 1
  968.      
  969.          def trace_dispatch_return(self, frame, t):
  970.              rt, rtt, frame, rcur = self.cur
  971.      
  972.              rfn = `frame.f_code`
  973.      
  974.              pt, ptt, pframe, pcur = rcur
  975.              self.cur = pt, ptt+rt, pframe, pcur
  976.      
  977.              if self.timings.has_key(rfn):
  978.                  nc, tt = self.timings[rfn]
  979.                  self.timings[rfn] = nc + 1, rt + rtt + tt
  980.              else:
  981.                  self.timings[rfn] =      1, rt + rtt
  982.      
  983.              return 1
  984.      
  985.      
  986.          def snapshot_stats(self):
  987.              self.stats = {}
  988.              for func in self.timings.keys():
  989.                  nc, tt = self.timings[func]
  990.                  nor_func = self.func_normalize(func)
  991.                  self.stats[nor_func] = nc, nc, tt, 0, {}
  992.  
  993. 
  994. File: pylibi,  Node: Internet and WWW,  Next: Restricted Execution,  Prev: The Python Profiler,  Up: Top
  995.  
  996. Internet and WWW Services
  997. *************************
  998.  
  999. The modules described in this chapter provide various services to
  1000. World-Wide Web (WWW) clients and/or services, and a few modules related
  1001. to news and email.  They are all implemented in Python.  Some of these
  1002. modules require the presence of the system-dependent module `sockets',
  1003. which is currently only fully supported on Unix and Windows NT.  Here
  1004. is an overview:
  1005.  
  1006. cgi
  1007.      -- Common Gateway Interface, used to interpret forms in server-side
  1008.      scripts.
  1009.  
  1010. urllib
  1011.      -- Open an arbitrary object given by URL (requires sockets).
  1012.  
  1013. httplib
  1014.      -- HTTP protocol client (requires sockets).
  1015.  
  1016. ftplib
  1017.      -- FTP protocol client (requires sockets).
  1018.  
  1019. gopherlib
  1020.      -- Gopher protocol client (requires sockets).
  1021.  
  1022. nntplib
  1023.      -- NNTP protocol client (requires sockets).
  1024.  
  1025. urlparse
  1026.      -- Parse a URL string into a tuple (addressing scheme identifier,
  1027.      network location, path, parameters, query string, fragment
  1028.      identifier).
  1029.  
  1030. sgmllib
  1031.      -- Only as much of an SGML parser as needed to parse HTML.
  1032.  
  1033. htmllib
  1034.      -- A (slow) parser for HTML documents.
  1035.  
  1036. formatter
  1037.      -- Generic output formatter and device interface.
  1038.  
  1039. rfc822
  1040.      -- Parse RFC-822 style mail headers.
  1041.  
  1042. mimetools
  1043.      -- Tools for parsing MIME style message bodies.
  1044.  
  1045. * Menu:
  1046.  
  1047. * cgi::
  1048. * urllib::
  1049. * httplib::
  1050. * ftplib::
  1051. * gopherlib::
  1052. * nntplib::
  1053. * urlparse::
  1054. * sgmllib::
  1055. * htmllib::
  1056. * formatter::
  1057. * rfc822::
  1058. * mimetools::
  1059. * binhex::
  1060. * uu::
  1061. * binascii::
  1062. * xdrlib::
  1063.  
  1064. 
  1065. File: pylibi,  Node: cgi,  Next: urllib,  Prev: Internet and WWW,  Up: Internet and WWW
  1066.  
  1067. Standard Module `cgi'
  1068. =====================
  1069.  
  1070. Support module for CGI (Common Gateway Interface) scripts.
  1071.  
  1072. This module defines a number of utilities for use by CGI scripts
  1073. written in Python.
  1074.  
  1075. * Menu:
  1076.  
  1077. * Introduction to the CGI module::
  1078. * Using the cgi module::
  1079. * Old classes::
  1080. * Functions::
  1081. * Caring about security::
  1082. * Installing your CGI script on a Unix system::
  1083. * Testing your CGI script::
  1084. * Debugging CGI scripts::
  1085. * Common problems and solutions::
  1086.  
  1087. 
  1088. File: pylibi,  Node: Introduction to the CGI module,  Next: Using the cgi module,  Prev: cgi,  Up: cgi
  1089.  
  1090. Introduction
  1091. ------------
  1092.  
  1093. A CGI script is invoked by an HTTP server, usually to process user
  1094. input submitted through an HTML `<FORM>' or `<ISINPUT>' element.
  1095.  
  1096. Most often, CGI scripts live in the server's special `cgi-bin'
  1097. directory.  The HTTP server places all sorts of information about the
  1098. request (such as the client's hostname, the requested URL, the query
  1099. string, and lots of other goodies) in the script's shell environment,
  1100. executes the script, and sends the script's output back to the client.
  1101.  
  1102. The script's input is connected to the client too, and sometimes the
  1103. form data is read this way; at other times the form data is passed via
  1104. the "query string" part of the URL.  This module (`cgi.py') is intended
  1105. to take care of the different cases and provide a simpler interface to
  1106. the Python script.  It also provides a number of utilities that help in
  1107. debugging scripts, and the latest addition is support for file uploads
  1108. from a form (if your browser supports it - Grail 0.3 and Netscape 2.0
  1109. do).
  1110.  
  1111. The output of a CGI script should consist of two sections, separated by
  1112. a blank line.  The first section contains a number of headers, telling
  1113. the client what kind of data is following.  Python code to generate a
  1114. minimal header section looks like this:
  1115.  
  1116.          print "Content-type: text/html"    # HTML is following
  1117.          print                # blank line, end of headers
  1118.  
  1119. The second section is usually HTML, which allows the client software to
  1120. display nicely formatted text with header, in-line images, etc.  Here's
  1121. Python code that prints a simple piece of HTML:
  1122.  
  1123.          print "<TITLE>CGI script output</TITLE>"
  1124.          print "<H1>This is my first CGI script</H1>"
  1125.          print "Hello, world!"
  1126.  
  1127. (It may not be fully legal HTML according to the letter of the
  1128. standard, but any browser will understand it.)
  1129.  
  1130. 
  1131. File: pylibi,  Node: Using the cgi module,  Next: Old classes,  Prev: Introduction to the CGI module,  Up: cgi
  1132.  
  1133. Using the cgi module
  1134. --------------------
  1135.  
  1136. Begin by writing `import cgi'.  Don't use `from cgi import *' - the
  1137. module defines all sorts of names for its own use or for backward
  1138. compatibility that you don't want in your namespace.
  1139.  
  1140. It's best to use the `FieldStorage' class.  The other classes define in
  1141. this module are provided mostly for backward compatibility.
  1142. Instantiate it exactly once, without arguments.  This reads the form
  1143. contents from standard input or the environment (depending on the value
  1144. of various environment variables set according to the CGI standard).
  1145. Since it may consume standard input, it should be instantiated only
  1146. once.
  1147.  
  1148. The `FieldStorage' instance can be accessed as if it were a Python
  1149. dictionary.  For instance, the following code (which assumes that the
  1150. `Content-type' header and blank line have already been printed) checks
  1151. that the fields `name' and `addr' are both set to a non-empty string:
  1152.  
  1153.          form = cgi.FieldStorage()
  1154.          form_ok = 0
  1155.          if form.has_key("name") and form.has_key("addr"):
  1156.              if form["name"].value != "" and form["addr"].value != "":
  1157.                  form_ok = 1
  1158.          if not form_ok:
  1159.              print "<H1>Error</H1>"
  1160.              print "Please fill in the name and addr fields."
  1161.              return
  1162.          ...further form processing here...
  1163.  
  1164. Here the fields, accessed through `form[key]', are themselves instances
  1165. of `FieldStorage' (or `MiniFieldStorage', depending on the form
  1166. encoding).
  1167.  
  1168. If the submitted form data contains more than one field with the same
  1169. name, the object retrieved by `form[key]' is not a `(Mini)FieldStorage'
  1170. instance but a list of such instances.  If you expect this possibility
  1171. (i.e., when your HTML form comtains multiple fields with the same
  1172. name), use the `type()' function to determine whether you have a single
  1173. instance or a list of instances.  For example, here's code that
  1174. concatenates any number of username fields, separated by commas:
  1175.  
  1176.          username = form["username"]
  1177.          if type(username) is type([]):
  1178.              # Multiple username fields specified
  1179.              usernames = ""
  1180.              for item in username:
  1181.                  if usernames:
  1182.                      # Next item -- insert comma
  1183.                      usernames = usernames + "," + item.value
  1184.                  else:
  1185.                      # First item -- don't insert comma
  1186.                      usernames = item.value
  1187.          else:
  1188.              # Single username field specified
  1189.              usernames = username.value
  1190.  
  1191. If a field represents an uploaded file, the value attribute reads the
  1192. entire file in memory as a string.  This may not be what you want.  You
  1193. can test for an uploaded file by testing either the filename attribute
  1194. or the file attribute.  You can then read the data at leasure from the
  1195. file attribute:
  1196.  
  1197.          fileitem = form["userfile"]
  1198.          if fileitem.file:
  1199.              # It's an uploaded file; count lines
  1200.              linecount = 0
  1201.              while 1:
  1202.                  line = fileitem.file.readline()
  1203.                  if not line: break
  1204.                  linecount = linecount + 1
  1205.  
  1206. The file upload draft standard entertains the possibility of uploading
  1207. multiple files from one field (using a recursive `multipart/*'
  1208. encoding).  When this occurs, the item will be a dictionary-like
  1209. FieldStorage item.  This can be determined by testing its type
  1210. attribute, which should have the value `multipart/form-data' (or
  1211. perhaps another string beginning with `multipart/'  It this case, it
  1212. can be iterated over recursively just like the top-level form object.
  1213.  
  1214. When a form is submitted in the "old" format (as the query string or as
  1215. a single data part of type `application/x-www-form-urlencoded'), the
  1216. items will actually be instances of the class `MiniFieldStorage'.  In
  1217. this case, the list, file and filename attributes are always `None'.
  1218.  
  1219. 
  1220. File: pylibi,  Node: Old classes,  Next: Functions,  Prev: Using the cgi module,  Up: cgi
  1221.  
  1222. Old classes
  1223. -----------
  1224.  
  1225. These classes, present in earlier versions of the `cgi' module, are
  1226. still supported for backward compatibility.  New applications should
  1227. use the FieldStorage class.
  1228.  
  1229. `SvFormContentDict': single value form content as dictionary; assumes
  1230. each field name occurs in the form only once.
  1231.  
  1232. `FormContentDict': multiple value form content as dictionary (the form
  1233. items are lists of values).  Useful if your form contains multiple
  1234. fields with the same name.
  1235.  
  1236. Other classes (`FormContent', `InterpFormContentDict') are present for
  1237. backwards compatibility with really old applications only.  If you still
  1238. use these and would be inconvenienced when they disappeared from a next
  1239. version of this module, drop me a note.
  1240.  
  1241. 
  1242. File: pylibi,  Node: Functions,  Next: Caring about security,  Prev: Old classes,  Up: cgi
  1243.  
  1244. Functions
  1245. ---------
  1246.  
  1247. These are useful if you want more control, or if you want to employ
  1248. some of the algorithms implemented in this module in other
  1249. circumstances.
  1250.  
  1251.  - function of module cgi: parse (FP)
  1252.      : Parse a query in the environment or from a file (default
  1253.      `sys.stdin').
  1254.  
  1255.  - function of module cgi: parse_qs (QS)
  1256.      : parse a query string given as a string argument (data of type
  1257.      `application/x-www-form-urlencoded').
  1258.  
  1259.  - function of module cgi: parse_multipart (FP, PDICT)
  1260.      : parse input of type `multipart/form-data' (for file uploads).
  1261.      Arguments are `fp' for the input file and `pdict' for the
  1262.      dictionary containing other parameters of `content-type' header
  1263.  
  1264.      Returns a dictionary just like `parse_qs()': keys are the field
  1265.      names, each value is a list of values for that field.  This is
  1266.      easy to use but not much good if you are expecting megabytes to be
  1267.      uploaded - in that case, use the `FieldStorage' class instead
  1268.      which is much more flexible.  Note that `content-type' is the raw,
  1269.      unparsed contents of the `content-type' header.
  1270.  
  1271.      Note that this does not parse nested multipart parts - use
  1272.      `FieldStorage' for that.
  1273.  
  1274.  - function of module cgi: parse_header (STRING)
  1275.      : parse a header like `Content-type' into a main content-type and
  1276.      a dictionary of parameters.
  1277.  
  1278.  - function of module cgi: test ()
  1279.      : robust test CGI script, usable as main program.  Writes minimal
  1280.      HTTP headers and formats all information provided to the script in
  1281.      HTML form.
  1282.  
  1283.  - function of module cgi: print_environ ()
  1284.      : format the shell environment in HTML.
  1285.  
  1286.  - function of module cgi: print_form (FORM)
  1287.      : format a form in HTML.
  1288.  
  1289.  - function of module cgi: print_directory ()
  1290.      : format the current directory in HTML.
  1291.  
  1292.  - function of module cgi: print_environ_usage ()
  1293.      : print a list of useful (used by CGI) environment variables in
  1294.      HTML.
  1295.  
  1296.  - function of module cgi: escape ()
  1297.      : convert the characters "`&'", "`<'" and "`>'" to HTML-safe
  1298.      sequences.  Use this if you need to display text that might contain
  1299.      such characters in HTML.  To translate URLs for inclusion in the
  1300.      HREF attribute of an `<A>' tag, use `urllib.quote()'.
  1301.  
  1302. 
  1303. File: pylibi,  Node: Caring about security,  Next: Installing your CGI script on a Unix system,  Prev: Functions,  Up: cgi
  1304.  
  1305. Caring about security
  1306. ---------------------
  1307.  
  1308. There's one important rule: if you invoke an external program (e.g.
  1309. via the `os.system()' or `os.popen()' functions), make very sure you
  1310. don't pass arbitrary strings received from the client to the shell.
  1311. This is a well-known security hole whereby clever hackers anywhere on
  1312. the web can exploit a gullible CGI script to invoke arbitrary shell
  1313. commands.  Even parts of the URL or field names cannot be trusted,
  1314. since the request doesn't have to come from your form!
  1315.  
  1316. To be on the safe side, if you must pass a string gotten from a form to
  1317. a shell command, you should make sure the string contains only
  1318. alphanumeric characters, dashes, underscores, and periods.
  1319.  
  1320.