Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Doc/faq/library.rst

    r2 r391  
    55=========================
    66
    7 .. contents::
     7.. only:: html
     8
     9   .. contents::
    810
    911General Library Questions
     
    1517Check :ref:`the Library Reference <library-index>` to see if there's a relevant
    1618standard library module.  (Eventually you'll learn what's in the standard
    17 library and will able to skip this step.)
     19library and will be able to skip this step.)
    1820
    1921For third-party packages, search the `Python Package Index
     
    2931dynamically loaded module implemented in C, C++ or other compiled language.
    3032In this case you may not have the source file or it may be something like
    31 mathmodule.c, somewhere in a C source directory (not on the Python Path).
     33:file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path).
    3234
    3335There are (at least) three kinds of modules in Python:
     
    6163
    6264If you would like the script to be independent of where the Python interpreter
    63 lives, you can use the "env" program.  Almost all Unix variants support the
    64 following, assuming the Python interpreter is in a directory on the user's
    65 $PATH::
     65lives, you can use the :program:`env` program.  Almost all Unix variants support
     66the following, assuming the Python interpreter is in a directory on the user's
     67:envvar:`PATH`::
    6668
    6769  #!/usr/bin/env python
    6870
    69 *Don't* do this for CGI scripts.  The $PATH variable for CGI scripts is often
    70 very minimal, so you need to use the actual absolute pathname of the
     71*Don't* do this for CGI scripts.  The :envvar:`PATH` variable for CGI scripts is
     72often very minimal, so you need to use the actual absolute pathname of the
    7173interpreter.
    7274
    73 Occasionally, a user's environment is so full that the /usr/bin/env program
    74 fails; or there's no env program at all.  In that case, you can try the
     75Occasionally, a user's environment is so full that the :program:`/usr/bin/env`
     76program fails; or there's no env program at all.  In that case, you can try the
    7577following hack (due to Alex Rezinsky)::
    7678
     
    9294.. XXX curses *is* built by default, isn't it?
    9395
    94 For Unix variants: The standard Python source distribution comes with a curses
    95 module in the ``Modules/`` subdirectory, though it's not compiled by default
    96 (note that this is not available in the Windows distribution -- there is no
    97 curses module for Windows).
    98 
    99 The curses module supports basic curses features as well as many additional
     96For Unix variants the standard Python source distribution comes with a curses
     97module in the :source:`Modules` subdirectory, though it's not compiled by default.
     98(Note that this is not available in the Windows distribution -- there is no
     99curses module for Windows.)
     100
     101The :mod:`curses` module supports basic curses features as well as many additional
    100102functions from ncurses and SYSV curses such as colour, alternative character set
    101103support, pads, and mouse support. This means the module isn't compatible with
     
    111113
    112114The :mod:`atexit` module provides a register function that is similar to C's
    113 onexit.
     115:c:func:`onexit`.
    114116
    115117
     
    141143Smalltalk testing frameworks.
    142144
    143 For testing, it helps to write the program so that it may be easily tested by
    144 using good modular design.  Your program should have almost all functionality
     145To make testing easier, you should use good modular design in your program.
     146Your program should have almost all functionality
    145147encapsulated in either functions or class methods -- and this sometimes has the
    146148surprising and delightful effect of making the program run faster (because local
     
    158160Once your program is organized as a tractable collection of functions and class
    159161behaviours you should write test functions that exercise the behaviours.  A test
    160 suite can be associated with each module which automates a sequence of tests.
     162suite that automates a sequence of tests can be associated with each module.
    161163This sounds like a lot of work, but since Python is so terse and flexible it's
    162164surprisingly easy.  You can make coding much more pleasant and fun by writing
     
    187189-----------------------------------------
    188190
    189 For Unix variants: There are several solutions.  It's straightforward to do this
     191For Unix variants there are several solutions.  It's straightforward to do this
    190192using curses, but curses is a fairly large module to learn.  Here's a solution
    191193without curses::
     
    206208           try:
    207209               c = sys.stdin.read(1)
    208                print "Got character", `c`
     210               print "Got character", repr(c)
    209211           except IOError: pass
    210212   finally:
     
    274276   time.sleep(10)
    275277
    276 Instead of trying to guess how long a :func:`time.sleep` delay will be enough,
     278Instead of trying to guess a good delay value for :func:`time.sleep`,
    277279it's better to use some kind of semaphore mechanism.  One idea is to use the
    278280:mod:`Queue` module to create a queue object, let each thread append a token to
     
    285287
    286288Use the :mod:`Queue` module to create a queue containing a list of jobs.  The
    287 :class:`~Queue.Queue` class maintains a list of objects with ``.put(obj)`` to
    288 add an item to the queue and ``.get()`` to return an item.  The class will take
    289 care of the locking necessary to ensure that each job is handed out exactly
    290 once.
     289:class:`~Queue.Queue` class maintains a list of objects and has a ``.put(obj)``
     290method that adds items to the queue and a ``.get()`` method to return them.
     291The class will take care of the locking necessary to ensure that each job is
     292handed out exactly once.
    291293
    292294Here's a trivial example::
     
    297299   # assumes there will be no more work and exits.
    298300   # (Realistically workers will run until terminated.)
    299    def worker ():
     301   def worker():
    300302       print 'Running worker'
    301303       time.sleep(0.1)
     
    330332When run, this will produce the following output:
    331333
     334.. code-block:: none
     335
    332336   Running worker
    333337   Running worker
     
    344348   ...
    345349
    346 Consult the module's documentation for more details; the ``Queue`` class
    347 provides a featureful interface.
     350Consult the module's documentation for more details; the :class:`~Queue.Queue`
     351class provides a featureful interface.
    348352
    349353
     
    351355----------------------------------------------------
    352356
    353 A global interpreter lock (GIL) is used internally to ensure that only one
    354 thread runs in the Python VM at a time.  In general, Python offers to switch
     357A :term:`global interpreter lock` (GIL) is used internally to ensure that only
     358one thread runs in the Python VM at a time.  In general, Python offers to switch
    355359among threads only between bytecode instructions; how frequently it switches can
    356360be set via :func:`sys.setcheckinterval`.  Each bytecode instruction and
     
    397401.. XXX link to dbeazley's talk about GIL?
    398402
    399 The Global Interpreter Lock (GIL) is often seen as a hindrance to Python's
     403The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's
    400404deployment on high-end multiprocessor server machines, because a multi-threaded
    401405Python program effectively only uses one CPU, due to the insistence that
     
    411415Since then, the idea of getting rid of the GIL has occasionally come up but
    412416nobody has found a way to deal with the expected slowdown, and users who don't
    413 use threads would not be happy if their code ran at half at the speed.  Greg's
     417use threads would not be happy if their code ran at half the speed.  Greg's
    414418free threading patch set has not been kept up-to-date for later Python versions.
    415419
     
    459463To truncate a file, open it using ``f = open(filename, "r+")``, and use
    460464``f.truncate(offset)``; offset defaults to the current seek position.  There's
    461 also ```os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where
    462 ``fd`` is the file descriptor (a small integer).
     465also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where
     466*fd* is the file descriptor (a small integer).
    463467
    464468The :mod:`shutil` module also contains a number of functions to work on files
     
    494498string.
    495499
    496 For data that is more regular (e.g. a homogeneous list of ints or thefloats),
     500For data that is more regular (e.g. a homogeneous list of ints or floats),
    497501you can also use the :mod:`array` module.
    498502
     
    504508integer representing the opened file.  :func:`os.popen` creates a high-level
    505509file object, the same type returned by the built-in :func:`open` function.
    506 Thus, to read n bytes from a pipe p created with :func:`os.popen`, you need to
     510Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to
    507511use ``p.read(n)``.
    508512
     
    523527Warning: in general it is unwise to do this because you can easily cause a
    524528deadlock where your process is blocked waiting for output from the child while
    525 the child is blocked waiting for input from you.  This can be caused because the
    526 parent expects the child to output more text than it does, or it can be caused
    527 by data being stuck in stdio buffers due to lack of flushing.  The Python parent
     529the child is blocked waiting for input from you.  This can be caused by the
     530parent expecting the child to output more text than it does or by data being
     531stuck in stdio buffers due to lack of flushing.  The Python parent
    528532can of course explicitly flush the data it sends to the child before it reads
    529533any output, but if the child is a naive C program it may have been written to
     
    545549the result back.  Unless the amount of data is very large, the easiest way to do
    546550this is to write it to a temporary file and run the command with that temporary
    547 file as input.  The standard module :mod:`tempfile` exports a ``mktemp()``
    548 function to generate unique temporary file names. ::
     551file as input.  The standard module :mod:`tempfile` exports a
     552:func:`~tempfile.mktemp` function to generate unique temporary file names. ::
    549553
    550554   import tempfile
     
    673677       sys.stdout.write(httpobj.getfile().read())
    674678
    675 Note that in general for URL-encoded POST operations, query strings must be
    676 quoted by using :func:`urllib.quote`.  For example to send name="Guy Steele,
    677 Jr."::
    678 
    679    >>> from urllib import quote
    680    >>> x = quote("Guy Steele, Jr.")
    681    >>> x
    682    'Guy%20Steele,%20Jr.'
    683    >>> query_string = "name="+x
    684    >>> query_string
    685    'name=Guy%20Steele,%20Jr.'
     679Note that in general for percent-encoded POST operations, query strings must be
     680quoted using :func:`urllib.urlencode`.  For example, to send
     681``name=Guy Steele, Jr.``::
     682
     683   >>> import urllib
     684   >>> urllib.urlencode({'name': 'Guy Steele, Jr.'})
     685   'name=Guy+Steele%2C+Jr.'
    686686
    687687
     
    691691.. XXX add modern template languages
    692692
    693 There are many different modules available:
    694 
    695 * HTMLgen is a class library of objects corresponding to all the HTML 3.2 markup
    696   tags. It's used when you are writing in Python and wish to synthesize HTML
    697   pages for generating a web or for CGI forms, etc.
    698 
    699 * DocumentTemplate and Zope Page Templates are two different systems that are
    700   part of Zope.
    701 
    702 * Quixote's PTL uses Python syntax to assemble strings of text.
    703 
    704 Consult the `Web Programming wiki pages
    705 <http://wiki.python.org/moin/WebProgramming>`_ for more links.
     693You can find a collection of useful links on the `Web Programming wiki page
     694<http://wiki.python.org/moin/WebProgramming>`_.
    706695
    707696
     
    732721
    733722A Unix-only alternative uses sendmail.  The location of the sendmail program
    734 varies between systems; sometimes it is ``/usr/lib/sendmail``, sometime
     723varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
    735724``/usr/sbin/sendmail``.  The sendmail manual page will help you out.  Here's
    736725some sample code::
     
    799788Python types to files and strings, and back again.  Although marshal does not do
    800789fancy things like store instances or handle shared references properly, it does
    801 run extremely fast.  For example loading a half megabyte of data may take less
     790run extremely fast.  For example, loading a half megabyte of data may take less
    802791than a third of a second.  This often beats doing something more complex and
    803792general such as using gdbm with pickle/shelve.
     
    809798.. XXX update this, default protocol is 2/3
    810799
    811 The default format used by the pickle module is a slow one that results in
    812 readable pickles.  Making it the default, but it would break backward
    813 compatibility::
     800By default :mod:`pickle` uses a relatively old and slow format for backward
     801compatibility.  You can however specify other protocol versions that are
     802faster::
    814803
    815804    largeString = 'z' * (100 * 1024)
Note: See TracChangeset for help on using the changeset viewer.