Changeset 391 for python/trunk/Doc/faq/library.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/faq/library.rst
r2 r391 5 5 ========================= 6 6 7 .. contents:: 7 .. only:: html 8 9 .. contents:: 8 10 9 11 General Library Questions … … 15 17 Check :ref:`the Library Reference <library-index>` to see if there's a relevant 16 18 standard library module. (Eventually you'll learn what's in the standard 17 library and will able to skip this step.)19 library and will be able to skip this step.) 18 20 19 21 For third-party packages, search the `Python Package Index … … 29 31 dynamically loaded module implemented in C, C++ or other compiled language. 30 32 In 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). 32 34 33 35 There are (at least) three kinds of modules in Python: … … 61 63 62 64 If 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 the64 following, assuming the Python interpreter is in a directory on the user's65 $PATH::65 lives, you can use the :program:`env` program. Almost all Unix variants support 66 the following, assuming the Python interpreter is in a directory on the user's 67 :envvar:`PATH`:: 66 68 67 69 #!/usr/bin/env python 68 70 69 *Don't* do this for CGI scripts. The $PATH variable for CGI scripts is often70 very minimal, so you need to use the actual absolute pathname of the71 *Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI scripts is 72 often very minimal, so you need to use the actual absolute pathname of the 71 73 interpreter. 72 74 73 Occasionally, a user's environment is so full that the /usr/bin/env program74 fails; or there's no env program at all. In that case, you can try the75 Occasionally, a user's environment is so full that the :program:`/usr/bin/env` 76 program fails; or there's no env program at all. In that case, you can try the 75 77 following hack (due to Alex Rezinsky):: 76 78 … … 92 94 .. XXX curses *is* built by default, isn't it? 93 95 94 For Unix variants : The standard Python source distribution comes with a curses95 module in the ``Modules/`` subdirectory, though it's not compiled by default96 ( note that this is not available in the Windows distribution -- there is no97 curses module for Windows ).98 99 The cursesmodule supports basic curses features as well as many additional96 For Unix variants the standard Python source distribution comes with a curses 97 module 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 99 curses module for Windows.) 100 101 The :mod:`curses` module supports basic curses features as well as many additional 100 102 functions from ncurses and SYSV curses such as colour, alternative character set 101 103 support, pads, and mouse support. This means the module isn't compatible with … … 111 113 112 114 The :mod:`atexit` module provides a register function that is similar to C's 113 onexit.115 :c:func:`onexit`. 114 116 115 117 … … 141 143 Smalltalk testing frameworks. 142 144 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 functionality145 To make testing easier, you should use good modular design in your program. 146 Your program should have almost all functionality 145 147 encapsulated in either functions or class methods -- and this sometimes has the 146 148 surprising and delightful effect of making the program run faster (because local … … 158 160 Once your program is organized as a tractable collection of functions and class 159 161 behaviours 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.162 suite that automates a sequence of tests can be associated with each module. 161 163 This sounds like a lot of work, but since Python is so terse and flexible it's 162 164 surprisingly easy. You can make coding much more pleasant and fun by writing … … 187 189 ----------------------------------------- 188 190 189 For Unix variants : There are several solutions. It's straightforward to do this191 For Unix variants there are several solutions. It's straightforward to do this 190 192 using curses, but curses is a fairly large module to learn. Here's a solution 191 193 without curses:: … … 206 208 try: 207 209 c = sys.stdin.read(1) 208 print "Got character", `c`210 print "Got character", repr(c) 209 211 except IOError: pass 210 212 finally: … … 274 276 time.sleep(10) 275 277 276 Instead of trying to guess how long a :func:`time.sleep` delay will be enough,278 Instead of trying to guess a good delay value for :func:`time.sleep`, 277 279 it's better to use some kind of semaphore mechanism. One idea is to use the 278 280 :mod:`Queue` module to create a queue object, let each thread append a token to … … 285 287 286 288 Use 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)`` to288 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)`` 290 method that adds items to the queue and a ``.get()`` method to return them. 291 The class will take care of the locking necessary to ensure that each job is 292 handed out exactly once. 291 293 292 294 Here's a trivial example:: … … 297 299 # assumes there will be no more work and exits. 298 300 # (Realistically workers will run until terminated.) 299 def worker 301 def worker(): 300 302 print 'Running worker' 301 303 time.sleep(0.1) … … 330 332 When run, this will produce the following output: 331 333 334 .. code-block:: none 335 332 336 Running worker 333 337 Running worker … … 344 348 ... 345 349 346 Consult the module's documentation for more details; the ``Queue`` class347 provides a featureful interface.350 Consult the module's documentation for more details; the :class:`~Queue.Queue` 351 class provides a featureful interface. 348 352 349 353 … … 351 355 ---------------------------------------------------- 352 356 353 A global interpreter lock (GIL) is used internally to ensure that only one354 thread runs in the Python VM at a time. In general, Python offers to switch357 A :term:`global interpreter lock` (GIL) is used internally to ensure that only 358 one thread runs in the Python VM at a time. In general, Python offers to switch 355 359 among threads only between bytecode instructions; how frequently it switches can 356 360 be set via :func:`sys.setcheckinterval`. Each bytecode instruction and … … 397 401 .. XXX link to dbeazley's talk about GIL? 398 402 399 The Global Interpreter Lock(GIL) is often seen as a hindrance to Python's403 The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's 400 404 deployment on high-end multiprocessor server machines, because a multi-threaded 401 405 Python program effectively only uses one CPU, due to the insistence that … … 411 415 Since then, the idea of getting rid of the GIL has occasionally come up but 412 416 nobody 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 atthe speed. Greg's417 use threads would not be happy if their code ran at half the speed. Greg's 414 418 free threading patch set has not been kept up-to-date for later Python versions. 415 419 … … 459 463 To truncate a file, open it using ``f = open(filename, "r+")``, and use 460 464 ``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`, where462 ``fd``is the file descriptor (a small integer).465 also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where 466 *fd* is the file descriptor (a small integer). 463 467 464 468 The :mod:`shutil` module also contains a number of functions to work on files … … 494 498 string. 495 499 496 For data that is more regular (e.g. a homogeneous list of ints or thefloats),500 For data that is more regular (e.g. a homogeneous list of ints or floats), 497 501 you can also use the :mod:`array` module. 498 502 … … 504 508 integer representing the opened file. :func:`os.popen` creates a high-level 505 509 file object, the same type returned by the built-in :func:`open` function. 506 Thus, to read n bytes from a pipe pcreated with :func:`os.popen`, you need to510 Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to 507 511 use ``p.read(n)``. 508 512 … … 523 527 Warning: in general it is unwise to do this because you can easily cause a 524 528 deadlock 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 b ecausethe526 parent expect s the child to output more text than it does, or it can be caused527 by data beingstuck in stdio buffers due to lack of flushing. The Python parent529 the child is blocked waiting for input from you. This can be caused by the 530 parent expecting the child to output more text than it does or by data being 531 stuck in stdio buffers due to lack of flushing. The Python parent 528 532 can of course explicitly flush the data it sends to the child before it reads 529 533 any output, but if the child is a naive C program it may have been written to … … 545 549 the result back. Unless the amount of data is very large, the easiest way to do 546 550 this 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. ::551 file as input. The standard module :mod:`tempfile` exports a 552 :func:`~tempfile.mktemp` function to generate unique temporary file names. :: 549 553 550 554 import tempfile … … 673 677 sys.stdout.write(httpobj.getfile().read()) 674 678 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.' 679 Note that in general for percent-encoded POST operations, query strings must be 680 quoted 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.' 686 686 687 687 … … 691 691 .. XXX add modern template languages 692 692 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. 693 You can find a collection of useful links on the `Web Programming wiki page 694 <http://wiki.python.org/moin/WebProgramming>`_. 706 695 707 696 … … 732 721 733 722 A Unix-only alternative uses sendmail. The location of the sendmail program 734 varies between systems; sometimes it is ``/usr/lib/sendmail``, sometime 723 varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes 735 724 ``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's 736 725 some sample code:: … … 799 788 Python types to files and strings, and back again. Although marshal does not do 800 789 fancy 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 less790 run extremely fast. For example, loading a half megabyte of data may take less 802 791 than a third of a second. This often beats doing something more complex and 803 792 general such as using gdbm with pickle/shelve. … … 809 798 .. XXX update this, default protocol is 2/3 810 799 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::800 By default :mod:`pickle` uses a relatively old and slow format for backward 801 compatibility. You can however specify other protocol versions that are 802 faster:: 814 803 815 804 largeString = 'z' * (100 * 1024)
Note:
See TracChangeset
for help on using the changeset viewer.