Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

Location:
python/vendor/current/Doc/faq
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Doc/faq/design.rst

    r2 r388  
    88Guido van Rossum believes that using indentation for grouping is extremely
    99elegant and contributes a lot to the clarity of the average Python program.
    10 Most people learn to love this feature after awhile.
     10Most people learn to love this feature after a while.
    1111
    1212Since there are no begin/end brackets there cannot be a disagreement between
     
    2929least slightly uneasy when reading (or being required to write) another style.
    3030
    31 Many coding styles place begin/end brackets on a line by themself.  This makes
     31Many coding styles place begin/end brackets on a line by themselves.  This makes
    3232programs considerably longer and wastes valuable screen space, making it harder
    3333to get a good overview of a program.  Ideally, a function should fit on one
     
    4949People are often very surprised by results like this::
    5050
    51    >>> 1.2-1.0
     51   >>> 1.2 - 1.0
    5252   0.199999999999999996
    5353
     
    7676that was probably intended::
    7777
    78    >>> 0.2
    79    0.20000000000000001
    80    >>> print 0.2
     78   >>> 1.1 - 0.9
     79   0.20000000000000007
     80   >>> print 1.1 - 0.9
    8181   0.2
    8282
     
    8686numbers is less than a certain threshold::
    8787
    88    epsilon = 0.0000000000001 # Tiny allowed error
     88   epsilon = 0.0000000000001  # Tiny allowed error
    8989   expected_result = 0.4
    9090
     
    132132reference or call the method from a particular class.  In C++, if you want to
    133133use a method from a base class which is overridden in a derived class, you have
    134 to use the ``::`` operator -- in Python you can write baseclass.methodname(self,
    135 <argument list>).  This is particularly useful for :meth:`__init__` methods, and
    136 in general in cases where a derived class method wants to extend the base class
    137 method of the same name and thus has to call the base class method somehow.
     134to use the ``::`` operator -- in Python you can write
     135``baseclass.methodname(self, <argument list>)``.  This is particularly useful
     136for :meth:`__init__` methods, and in general in cases where a derived class
     137method wants to extend the base class method of the same name and thus has to
     138call the base class method somehow.
    138139
    139140Finally, for instance variables it solves a syntactic problem with assignment:
    140141since local variables in Python are (by definition!) those variables to which a
    141 value assigned in a function body (and that aren't explicitly declared global),
    142 there has to be some way to tell the interpreter that an assignment was meant to
    143 assign to an instance variable instead of to a local variable, and it should
    144 preferably be syntactic (for efficiency reasons).  C++ does this through
     142value is assigned in a function body (and that aren't explicitly declared
     143global), there has to be some way to tell the interpreter that an assignment was
     144meant to assign to an instance variable instead of to a local variable, and it
     145should preferably be syntactic (for efficiency reasons).  C++ does this through
    145146declarations, but Python doesn't have declarations and it would be a pity having
    146 to introduce them just for this purpose.  Using the explicit "self.var" solves
     147to introduce them just for this purpose.  Using the explicit ``self.var`` solves
    147148this nicely.  Similarly, for using instance variables, having to write
    148 "self.var" means that references to unqualified names inside a method don't have
    149 to search the instance's directories.  To put it another way, local variables
    150 and instance variables live in two different namespaces, and you need to tell
    151 Python which namespace to use.
     149``self.var`` means that references to unqualified names inside a method don't
     150have to search the instance's directories.  To put it another way, local
     151variables and instance variables live in two different namespaces, and you need
     152to tell Python which namespace to use.
    152153
    153154
     
    225226that didn't have methods at all (e.g. tuples).  It is also convenient to have a
    226227function that can readily be applied to an amorphous collection of objects when
    227 you use the functional features of Python (``map()``, ``apply()`` et al).
     228you use the functional features of Python (``map()``, ``zip()`` et al).
    228229
    229230In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is
     
    235236.. XXX talk about protocols?
    236237
    237 Note that for string operations Python has moved from external functions (the
    238 ``string`` module) to methods.  However, ``len()`` is still a function.
     238.. note::
     239
     240   For string operations, Python has moved from external functions (the
     241   ``string`` module) to methods.  However, ``len()`` is still a function.
    239242
    240243
     
    295298------------------------
    296299
    297 A try/except block is extremely efficient.  Actually catching an exception is
    298 expensive.  In versions of Python prior to 2.0 it was common to use this idiom::
     300A try/except block is extremely efficient if no exceptions are raised.  Actually
     301catching an exception is expensive.  In versions of Python prior to 2.0 it was
     302common to use this idiom::
    299303
    300304   try:
    301        value = dict[key]
     305       value = mydict[key]
    302306   except KeyError:
    303        dict[key] = getvalue(key)
    304        value = dict[key]
     307       mydict[key] = getvalue(key)
     308       value = mydict[key]
    305309
    306310This only made sense when you expected the dict to have the key almost all the
    307311time.  If that wasn't the case, you coded it like this::
    308312
    309    if dict.has_key(key):
    310        value = dict[key]
     313   if key in mydict:
     314       value = mydict[key]
    311315   else:
    312        dict[key] = getvalue(key)
    313        value = dict[key]
    314 
    315 (In Python 2.0 and higher, you can code this as ``value = dict.setdefault(key,
    316 getvalue(key))``.)
     316       value = mydict[key] = getvalue(key)
     317
     318.. note::
     319
     320   In Python 2.0 and higher, you can code this as ``value =
     321   mydict.setdefault(key, getvalue(key))``.
    317322
    318323
     
    366371Answer 2: Fortunately, there is `Stackless Python <http://www.stackless.com>`_,
    367372which has a completely redesigned interpreter loop that avoids the C stack.
    368 It's still experimental but looks very promising.  Although it is binary
    369 compatible with standard Python, it's still unclear whether Stackless will make
    370 it into the core -- maybe it's just too revolutionary.
    371 
    372 
    373 Why can't lambda forms contain statements?
    374 ------------------------------------------
    375 
    376 Python lambda forms cannot contain statements because Python's syntactic
     373
     374
     375Why can't lambda expressions contain statements?
     376------------------------------------------------
     377
     378Python lambda expressions cannot contain statements because Python's syntactic
    377379framework can't handle statements nested inside expressions.  However, in
    378380Python, this is not a serious problem.  Unlike lambda forms in other languages,
     
    381383
    382384Functions are already first class objects in Python, and can be declared in a
    383 local scope.  Therefore the only advantage of using a lambda form instead of a
     385local scope.  Therefore the only advantage of using a lambda instead of a
    384386locally-defined function is that you don't need to invent a name for the
    385387function -- but that's just a local variable to which the function object (which
    386 is exactly the same type of object that a lambda form yields) is assigned!
     388is exactly the same type of object that a lambda expression yields) is assigned!
    387389
    388390
     
    433435<http://pyinline.sourceforge.net/>`_, `Py2Cmod
    434436<http://sourceforge.net/projects/py2cmod/>`_, and `Weave
    435 <http://www.scipy.org/site_content/weave>`_.
     437<http://www.scipy.org/Weave>`_.
    436438
    437439
     
    451453the behavior of the reference counting implementation.
    452454
     455.. XXX relevant for Python 2.6?
     456
    453457Sometimes objects get stuck in tracebacks temporarily and hence are not
    454458deallocated when you might expect.  Clear the tracebacks with::
     
    462466handling of an exception (usually the most recent exception).
    463467
    464 In the absence of circularities and tracebacks, Python programs need not
    465 explicitly manage memory.
     468In the absence of circularities and tracebacks, Python programs do not need to
     469manage memory explicitly.
    466470
    467471Why doesn't Python use a more traditional garbage collection scheme?  For one
     
    482486of file descriptors long before it runs out of memory::
    483487
    484    for file in <very long list of files>:
     488   for file in very_long_list_of_files:
    485489       f = open(file)
    486490       c = f.read(1)
     
    489493to f closes the previous file.  Using GC, this is not guaranteed.  If you want
    490494to write code that will work with any Python implementation, you should
    491 explicitly close the file; this will work regardless of GC::
    492 
    493    for file in <very long list of files>:
    494        f = open(file)
    495        c = f.read(1)
    496        f.close()
     495explicitly close the file or use the :keyword:`with` statement; this will work
     496regardless of GC::
     497
     498   for file in very_long_list_of_files:
     499       with open(file) as f:
     500           c = f.read(1)
    497501
    498502
     
    590594  construct a new list with the same value it won't be found; e.g.::
    591595
    592      d = {[1,2]: '12'}
    593      print d[[1,2]]
    594 
    595   would raise a KeyError exception because the id of the ``[1,2]`` used in the
     596     mydict = {[1, 2]: '12'}
     597     print mydict[[1, 2]]
     598
     599  would raise a KeyError exception because the id of the ``[1, 2]`` used in the
    596600  second line differs from that in the first line.  In other words, dictionary
    597601  keys should be compared using ``==``, not using :keyword:`is`.
     
    614618There is a trick to get around this if you need to, but use it at your own risk:
    615619You can wrap a mutable structure inside a class instance which has both a
    616 :meth:`__cmp_` and a :meth:`__hash__` method.  You must then make sure that the
     620:meth:`__eq__` and a :meth:`__hash__` method.  You must then make sure that the
    617621hash value for all such wrapper objects that reside in a dictionary (or other
    618622hash based structure), remain fixed while the object is in the dictionary (or
     
    622626       def __init__(self, the_list):
    623627           self.the_list = the_list
    624        def __cmp__(self, other):
     628       def __eq__(self, other):
    625629           return self.the_list == other.the_list
    626630       def __hash__(self):
    627631           l = self.the_list
    628632           result = 98767 - len(l)*555
    629            for i in range(len(l)):
     633           for i, el in enumerate(l):
    630634               try:
    631                    result = result + (hash(l[i]) % 9999999) * 1001 + i
    632                except:
     635                   result = result + (hash(el) % 9999999) * 1001 + i
     636               except Exception:
    633637                   result = (result % 7777777) + i * 333
    634638           return result
     
    638642overflow.
    639643
    640 Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__cmp__(o2)
    641 == 0``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``),
     644Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__eq__(o2)
     645is True``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``),
    642646regardless of whether the object is in a dictionary or not.  If you fail to meet
    643647these restrictions dictionaries and other hash based structures will misbehave.
     
    663667order::
    664668
    665    for key in sorted(dict.iterkeys()):
    666        ... # do whatever with dict[key]...
     669   for key in sorted(mydict):
     670       ... # do whatever with mydict[key]...
    667671
    668672
     
    678682(ABCs).  You can then use :func:`isinstance` and :func:`issubclass` to check
    679683whether an instance or a class implements a particular ABC.  The
    680 :mod:`collections` modules defines a set of useful ABCs such as
    681 :class:`Iterable`, :class:`Container`, and :class:`MutableMapping`.
     684:mod:`collections` module defines a set of useful ABCs such as
     685:class:`~collections.Iterable`, :class:`~collections.Container`, and
     686:class:`~collections.MutableMapping`.
    682687
    683688For Python, many of the advantages of interface specifications can be obtained
     
    713718This type of bug commonly bites neophyte programmers.  Consider this function::
    714719
    715    def foo(D={}):  # Danger: shared reference to one dict for all calls
     720   def foo(mydict={}):  # Danger: shared reference to one dict for all calls
    716721       ... compute something ...
    717        D[key] = value
    718        return D
    719 
    720 The first time you call this function, ``D`` contains a single item.  The second
    721 time, ``D`` contains two items because when ``foo()`` begins executing, ``D``
    722 starts out with an item already in it.
     722       mydict[key] = value
     723       return mydict
     724
     725The first time you call this function, ``mydict`` contains a single item.  The
     726second time, ``mydict`` contains two items because when ``foo()`` begins
     727executing, ``mydict`` starts out with an item already in it.
    723728
    724729It is often expected that a function call creates new objects for default
     
    736741list/dictionary/whatever if it is.  For example, don't write::
    737742
    738    def foo(dict={}):
     743   def foo(mydict={}):
    739744       ...
    740745
    741746but::
    742747
    743    def foo(dict=None):
    744        if dict is None:
    745            dict = {} # create a new dict for local namespace
     748   def foo(mydict=None):
     749       if mydict is None:
     750           mydict = {} # create a new dict for local namespace
    746751
    747752This feature can be useful.  When you have a function that's time-consuming to
     
    751756
    752757   # Callers will never provide a third parameter for this function.
    753    def expensive (arg1, arg2, _cache={}):
    754        if _cache.has_key((arg1, arg2)):
     758   def expensive(arg1, arg2, _cache={}):
     759       if (arg1, arg2) in _cache:
    755760           return _cache[(arg1, arg2)]
    756761
     
    772777languages.  For example::
    773778
    774    class label: pass # declare a label
     779   class label: pass  # declare a label
    775780
    776781   try:
    777782        ...
    778         if (condition): raise label() # goto label
     783        if condition: raise label() # goto label
    779784        ...
    780    except label: # where to goto
     785   except label:  # where to goto
    781786        pass
    782787   ...
     
    803808accept forward slashes too::
    804809
    805    f = open("/mydir/file.txt") # works fine!
     810   f = open("/mydir/file.txt")  # works fine!
    806811
    807812If you're trying to build a pathname for a DOS command, try e.g. one of ::
     
    820825
    821826   with obj:
    822        a = 1    # equivalent to obj.a = 1
     827       a = 1               # equivalent to obj.a = 1
    823828       total = total + 1   # obj.total = obj.total + 1
    824829
     
    851856volume) can, however, easily be achieved in Python by assignment.  Instead of::
    852857
    853    function(args).dict[index][index].a = 21
    854    function(args).dict[index][index].b = 42
    855    function(args).dict[index][index].c = 63
     858   function(args).mydict[index][index].a = 21
     859   function(args).mydict[index][index].b = 42
     860   function(args).mydict[index][index].c = 63
    856861
    857862write this::
    858863
    859    ref = function(args).dict[index][index]
     864   ref = function(args).mydict[index][index]
    860865   ref.a = 21
    861866   ref.b = 42
     
    864869This also has the side-effect of increasing execution speed because name
    865870bindings are resolved at run-time in Python, and the second version only needs
    866 to perform the resolution once.  If the referenced object does not have a, b and
    867 c attributes, of course, the end result is still a run-time exception.
     871to perform the resolution once.
    868872
    869873
     
    908912When you have a literal value for a list, tuple, or dictionary spread across
    909913multiple lines, it's easier to add more elements because you don't have to
    910 remember to add a comma to the previous line.  The lines can also be sorted in
    911 your editor without creating a syntax error.
     914remember to add a comma to the previous line.  The lines can also be reordered
     915without creating a syntax error.
    912916
    913917Accidentally omitting the comma can lead to errors that are hard to diagnose.
  • python/vendor/current/Doc/faq/extending.rst

    r2 r388  
    33=======================
    44
    5 .. contents::
     5.. only:: html
     6
     7   .. contents::
    68
    79.. highlight:: c
     
    2628C++ objects with constructors are probably not a good idea.
    2729
     30
     31.. _c-wrapper-software:
    2832
    2933Writing C is hard; are there any alternatives?
     
    5256<http://cxx.sourceforge.net/>`_ `Boost
    5357<http://www.boost.org/libs/python/doc/index.html>`_, or `Weave
    54 <http://www.scipy.org/site_content/weave>`_ are also alternatives for wrapping
     58<http://www.scipy.org/Weave>`_ are also alternatives for wrapping
    5559C++ libraries.
    5660
     
    5963-----------------------------------------------------
    6064
    61 The highest-level function to do this is :cfunc:`PyRun_SimpleString` which takes
     65The highest-level function to do this is :c:func:`PyRun_SimpleString` which takes
    6266a single string argument to be executed in the context of the module
    6367``__main__`` and returns 0 for success and -1 when an exception occurred
    6468(including ``SyntaxError``).  If you want more control, use
    65 :cfunc:`PyRun_String`; see the source for :cfunc:`PyRun_SimpleString` in
     69:c:func:`PyRun_String`; see the source for :c:func:`PyRun_SimpleString` in
    6670``Python/pythonrun.c``.
    6771
     
    7074---------------------------------------------------------
    7175
    72 Call the function :cfunc:`PyRun_String` from the previous question with the
    73 start symbol :cdata:`Py_eval_input`; it parses an expression, evaluates it and
     76Call the function :c:func:`PyRun_String` from the previous question with the
     77start symbol :c:data:`Py_eval_input`; it parses an expression, evaluates it and
    7478returns its value.
    7579
     
    7882-----------------------------------------------
    7983
    80 That depends on the object's type.  If it's a tuple, :cfunc:`PyTuple_Size`
    81 returns its length and :cfunc:`PyTuple_GetItem` returns the item at a specified
    82 index.  Lists have similar functions, :cfunc:`PyListSize` and
    83 :cfunc:`PyList_GetItem`.
    84 
    85 For strings, :cfunc:`PyString_Size` returns its length and
    86 :cfunc:`PyString_AsString` a pointer to its value.  Note that Python strings may
    87 contain null bytes so C's :cfunc:`strlen` should not be used.
     84That depends on the object's type.  If it's a tuple, :c:func:`PyTuple_Size`
     85returns its length and :c:func:`PyTuple_GetItem` returns the item at a specified
     86index.  Lists have similar functions, :c:func:`PyListSize` and
     87:c:func:`PyList_GetItem`.
     88
     89For strings, :c:func:`PyString_Size` returns its length and
     90:c:func:`PyString_AsString` a pointer to its value.  Note that Python strings may
     91contain null bytes so C's :c:func:`strlen` should not be used.
    8892
    8993To test the type of an object, first make sure it isn't *NULL*, and then use
    90 :cfunc:`PyString_Check`, :cfunc:`PyTuple_Check`, :cfunc:`PyList_Check`, etc.
     94:c:func:`PyString_Check`, :c:func:`PyTuple_Check`, :c:func:`PyList_Check`, etc.
    9195
    9296There is also a high-level API to Python objects which is provided by the
    9397so-called 'abstract' interface -- read ``Include/abstract.h`` for further
    9498details.  It allows interfacing with any kind of Python sequence using calls
    95 like :cfunc:`PySequence_Length`, :cfunc:`PySequence_GetItem`, etc.)  as well as
     99like :c:func:`PySequence_Length`, :c:func:`PySequence_GetItem`, etc.)  as well as
    96100many other useful protocols.
    97101
     
    102106You can't.  Use ``t = PyTuple_New(n)`` instead, and fill it with objects using
    103107``PyTuple_SetItem(t, i, o)`` -- note that this "eats" a reference count of
    104 ``o``, so you have to :cfunc:`Py_INCREF` it.  Lists have similar functions
     108``o``, so you have to :c:func:`Py_INCREF` it.  Lists have similar functions
    105109``PyList_New(n)`` and ``PyList_SetItem(l, i, o)``.  Note that you *must* set all
    106110the tuple items to some value before you pass the tuple to Python code --
     
    111115----------------------------------------
    112116
    113 The :cfunc:`PyObject_CallMethod` function can be used to call an arbitrary
     117The :c:func:`PyObject_CallMethod` function can be used to call an arbitrary
    114118method of an object.  The parameters are the object, the name of the method to
    115 call, a format string like that used with :cfunc:`Py_BuildValue`, and the
     119call, a format string like that used with :c:func:`Py_BuildValue`, and the
    116120argument values::
    117121
     
    121125
    122126This works for any object that has methods -- whether built-in or user-defined.
    123 You are responsible for eventually :cfunc:`Py_DECREF`\ 'ing the return value.
     127You are responsible for eventually :c:func:`Py_DECREF`\ 'ing the return value.
    124128
    125129To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the
     
    134138   }
    135139
    136 Note that since :cfunc:`PyObject_CallObject` *always* wants a tuple for the
     140Note that since :c:func:`PyObject_CallObject` *always* wants a tuple for the
    137141argument list, to call a function without arguments, pass "()" for the format,
    138142and to call a function with one argument, surround the argument in parentheses,
     
    185189   attr = PyObject_GetAttrString(module, "<attrname>");
    186190
    187 Calling :cfunc:`PyObject_SetAttrString` to assign to variables in the module
     191Calling :c:func:`PyObject_SetAttrString` to assign to variables in the module
    188192also works.
    189193
     
    198202Python type around a C structure (pointer) type will also work for C++ objects.
    199203
    200 For C++ libraries, you can look at `SIP
    201 <http://www.riverbankcomputing.co.uk/sip/>`_, `CXX
    202 <http://cxx.sourceforge.net/>`_, `Boost
    203 <http://www.boost.org/libs/python/doc/index.html>`_, `Weave
    204 <http://www.scipy.org/site_content/weave>`_ or `SWIG <http://www.swig.org>`_
     204For C++ libraries, see :ref:`c-wrapper-software`.
    205205
    206206
     
    270270behavior sufficiently.  IDLE uses this, for example.
    271271
    272 The easiest way to do it in C is to call :cfunc:`PyRun_InteractiveLoop` (perhaps
     272The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` (perhaps
    273273in a separate thread) and let the Python interpreter handle the input for
    274 you. You can also set the :cfunc:`PyOS_ReadlineFunctionPointer` to point at your
     274you. You can also set the :c:func:`PyOS_ReadlineFunctionPointer` to point at your
    275275custom input function. See ``Modules/readline.c`` and ``Parser/myreadline.c``
    276276for more hints.
     
    278278However sometimes you have to run the embedded Python interpreter in the same
    279279thread as your rest application and you can't allow the
    280 :cfunc:`PyRun_InteractiveLoop` to stop while waiting for user input.  The one
    281 solution then is to call :cfunc:`PyParser_ParseString` and test for ``e.error``
     280:c:func:`PyRun_InteractiveLoop` to stop while waiting for user input.  The one
     281solution then is to call :c:func:`PyParser_ParseString` and test for ``e.error``
    282282equal to ``E_EOF``, which means the input is incomplete).  Here's a sample code
    283283fragment, untested, inspired by code from Alex Farber::
     
    310310
    311311Another solution is trying to compile the received string with
    312 :cfunc:`Py_CompileString`. If it compiles without errors, try to execute the
    313 returned code object by calling :cfunc:`PyEval_EvalCode`. Otherwise save the
     312:c:func:`Py_CompileString`. If it compiles without errors, try to execute the
     313returned code object by calling :c:func:`PyEval_EvalCode`. Otherwise save the
    314314input for later. If the compilation fails, find out if it's an error or just
    315315more input is required - by extracting the message string from the exception
     
    463463Unicode.  This only causes the link failure if the extension uses any of the
    464464``PyUnicode_*()`` functions.  It is also a problem if an extension uses any of
    465 the Unicode-related format specifiers for :cfunc:`Py_BuildValue` (or similar) or
    466 parameter specifications for :cfunc:`PyArg_ParseTuple`.
     465the Unicode-related format specifiers for :c:func:`Py_BuildValue` (or similar) or
     466parameter specifications for :c:func:`PyArg_ParseTuple`.
    467467
    468468You can check the size of the Unicode character a Python interpreter is using by
  • python/vendor/current/Doc/faq/general.rst

    r2 r388  
    55==================
    66
    7 .. contents::
     7.. only:: html
     8
     9   .. contents::
     10
    811
    912General Information
     
    158161The latest Python source distribution is always available from python.org, at
    159162http://www.python.org/download/.  The latest development sources can be obtained
    160 via anonymous Subversion at http://svn.python.org/projects/python/trunk.
     163via anonymous Mercurial access at http://hg.python.org/cpython.
    161164
    162165The source distribution is a gzipped tar file containing the complete C source,
     
    165168and run out of the box on most UNIX platforms.
    166169
    167 .. XXX update link once the dev faq is relocated
    168 
    169 Consult the `Developer FAQ <http://www.python.org/dev/faq/>`__ for more
     170Consult the `Developer FAQ <http://docs.python.org/devguide/faq>`__ for more
    170171information on getting the source code and compiling it.
    171172
     
    222223news is available.
    223224
    224 .. XXX update link once the dev faq is relocated
    225 
    226225You can also access the development version of Python through Subversion.  See
    227 http://www.python.org/dev/faq/ for details.
     226http://docs.python.org/devguide/faq for details.
    228227
    229228
     
    240239`password reset procedure <http://bugs.python.org/user?@template=forgotten>`_.
    241240
    242 .. XXX adapt link to dev guide
    243 
    244241For more information on how Python is developed, consult `the Python Developer's
    245 Guide <http://python.org/dev/>`_.
     242Guide <http://docs.python.org/devguide/>`_.
    246243
    247244
  • python/vendor/current/Doc/faq/gui.rst

    r2 r388  
    55==========================
    66
    7 .. contents::
     7.. only:: html
    88
    9 General GUI Questions
    10 =====================
     9   .. contents::
    1110
    1211What platform-independent GUI toolkits exist for Python?
    13 --------------------------------------------------------
     12========================================================
    1413
    1514Depending on what platform(s) you are aiming at, there are several.
     
    1817
    1918Tkinter
    20 '''''''
     19-------
    2120
    2221Standard builds of Python include an object-oriented interface to the Tcl/Tk
     
    2726
    2827wxWidgets
    29 '''''''''
     28---------
    3029
    31 wxWidgets is a GUI class library written in C++ that's a portable
    32 interface to various platform-specific libraries, and that has a
    33 Python interface called `wxPython <http://www.wxpython.org>`__.
     30wxWidgets (http://www.wxwidgets.org) is a free, portable GUI class
     31library written in C++ that provides a native look and feel on a
     32number of platforms, with Windows, MacOS X, GTK, X11, all listed as
     33current stable targets.  Language bindings are available for a number
     34of languages including Python, Perl, Ruby, etc.
    3435
    35 wxWidgets preserves the look and feel of the
    36 underlying graphics toolkit, and has a large set of widgets and
    37 collection of GDI classes.  See `the wxWidgets page
    38 <http://www.wxwidgets.org>`_ for more details.
     36wxPython (http://www.wxpython.org) is the Python binding for
     37wxwidgets.  While it often lags slightly behind the official wxWidgets
     38releases, it also offers a number of features via pure Python
     39extensions that are not available in other language bindings.  There
     40is an active wxPython user and developer community.
    3941
    40 wxWidgets supports Windows and MacOS; on Unix variants,
    41 it supports both GTk+ and Motif toolkits.
     42Both wxWidgets and wxPython are free, open source, software with
     43permissive licences that allow their use in commercial products as
     44well as in freeware or shareware.
     45
    4246
    4347Qt
    44 '''
     48---
    4549
    46 There are bindings available for the Qt toolkit (`PyQt
    47 <http://www.riverbankcomputing.co.uk/software/pyqt/>`_) and for KDE (`PyKDE <http://www.riverbankcomputing.co.uk/software/pykde/intro>`__).  If
    48 you're writing open source software, you don't need to pay for PyQt, but if you
    49 want to write proprietary applications, you must buy a PyQt license from
    50 `Riverbank Computing <http://www.riverbankcomputing.co.uk>`_ and (up to Qt 4.4;
    51 Qt 4.5 upwards is licensed under the LGPL license) a Qt license from `Trolltech
    52 <http://www.trolltech.com>`_.
     50There are bindings available for the Qt toolkit (using either `PyQt
     51<http://www.riverbankcomputing.co.uk/software/pyqt/>`_ or `PySide
     52<http://www.pyside.org/>`_) and for KDE (`PyKDE <http://www.riverbankcomputing.co.uk/software/pykde/intro>`_).
     53PyQt is currently more mature than PySide, but you must buy a PyQt license from
     54`Riverbank Computing <http://www.riverbankcomputing.co.uk/software/pyqt/license>`_
     55if you want to write proprietary applications.  PySide is free for all applications.
     56
     57Qt 4.5 upwards is licensed under the LGPL license; also, commercial licenses
     58are available from `Nokia <http://qt.nokia.com/>`_.
    5359
    5460Gtk+
    55 ''''
     61----
    5662
    5763PyGtk bindings for the `Gtk+ toolkit <http://www.gtk.org>`_ have been
     
    5965
    6066FLTK
    61 ''''
     67----
    6268
    6369Python bindings for `the FLTK toolkit <http://www.fltk.org>`_, a simple yet
     
    6773
    6874FOX
    69 '''
     75----
    7076
    7177A wrapper for `the FOX toolkit <http://www.fox-toolkit.org/>`_ called `FXpy
     
    7581
    7682OpenGL
    77 ''''''
     83------
    7884
    7985For OpenGL bindings, see `PyOpenGL <http://pyopengl.sourceforge.net>`_.
     
    8187
    8288What platform-specific GUI toolkits exist for Python?
    83 -----------------------------------------------------
     89========================================================
    8490
    8591`The Mac port <http://python.org/download/mac>`_ by Jack Jansen has a rich and
     
    116122
    117123Build Tix with SAM enabled, perform the appropriate call to
    118 :cfunc:`Tclsam_init`, etc. inside Python's
     124:c:func:`Tclsam_init`, etc. inside Python's
    119125:file:`Modules/tkappinit.c`, and link with libtclsam and libtksam (you
    120126might include the Tix libraries as well).
     
    125131
    126132Yes, and you don't even need threads!  But you'll have to restructure your I/O
    127 code a bit.  Tk has the equivalent of Xt's :cfunc:`XtAddInput()` call, which allows you
     133code a bit.  Tk has the equivalent of Xt's :c:func:`XtAddInput()` call, which allows you
    128134to register a callback function which will be called from the Tk mainloop when
    129135I/O is possible on a file descriptor.  Here's what you need::
  • python/vendor/current/Doc/faq/index.rst

    r2 r388  
     1.. _faq-index:
     2
    13###################################
    24  Python Frequently Asked Questions
    35###################################
    4 
    5 :Release: |version|
    6 :Date: |today|
    76
    87.. toctree::
  • python/vendor/current/Doc/faq/library.rst

    r2 r388  
    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)
  • python/vendor/current/Doc/faq/programming.rst

    r2 r388  
    55===============
    66
    7 .. contents::
     7.. only:: html
     8
     9   .. contents::
    810
    911General Questions
     
    172174
    173175   L2 = []
    174    for i in range[3]:
     176   for i in range(3):
    175177       L2.append(L1[i])
    176178
    177179it is much shorter and far faster to use ::
    178180
    179    L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
     181   L2 = list(L1[:3])  # "list" is redundant if L1 is a list.
    180182
    181183Note that the functionally-oriented built-in functions such as :func:`map`,
     
    184186together::
    185187
    186    >>> zip([1,2,3], [4,5,6])
     188   >>> zip([1, 2, 3], [4, 5, 6])
    187189   [(1, 4), (2, 5), (3, 6)]
    188190
    189191or to compute a number of sines::
    190192
    191    >>> map( math.sin, (1,2,3,4))
    192    [0.841470984808, 0.909297426826, 0.14112000806,   -0.756802495308]
     193   >>> map(math.sin, (1, 2, 3, 4))
     194   [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]
    193195
    194196The operation completes very quickly in such cases.
    195197
    196 Other examples include the ``join()`` and ``split()`` methods of string objects.
     198Other examples include the ``join()`` and ``split()`` :ref:`methods
     199of string objects <string-methods>`.
    197200For example if s1..s7 are large (10K+) strings then
    198201``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious
    199202``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many
    200203subexpressions, whereas ``join()`` does all the copying in one pass.  For
    201 manipulating strings, use the ``replace()`` method on string objects. Use
    202 regular expressions only when you're not dealing with constant string patterns.
    203 Consider using the string formatting operations ``string % tuple`` and ``string
    204 % dictionary``.
     204manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods
     205on string objects <string-methods>`.  Use regular expressions only when you're
     206not dealing with constant string patterns.  You may still use :ref:`the old %
     207operations <string-formatting>` ``string % tuple`` and ``string % dictionary``.
    205208
    206209Be sure to use the :meth:`list.sort` built-in method to do sorting, and see the
     
    212215suppose you have a program that runs slowly and you use the profiler to
    213216determine that a Python function ``ff()`` is being called lots of times.  If you
    214 notice that ``ff ()``::
     217notice that ``ff()``::
    215218
    216219   def ff(x):
     
    333336   11
    334337
    335 In Python3, you can do a similar thing in a nested scope using the
    336 :keyword:`nonlocal` keyword:
    337 
    338 .. doctest::
    339    :options: +SKIP
    340 
    341    >>> def foo():
    342    ...    x = 10
    343    ...    def bar():
    344    ...        nonlocal x
    345    ...        print x
    346    ...        x += 1
    347    ...    bar()
    348    ...    print x
    349    >>> foo()
    350    10
    351    11
    352 
    353338
    354339What are the rules for local and global variables in Python?
     
    370355
    371356
     357Why do lambdas defined in a loop with different values all return the same result?
     358----------------------------------------------------------------------------------
     359
     360Assume you use a for loop to define a few different lambdas (or even plain
     361functions), e.g.::
     362
     363   >>> squares = []
     364   >>> for x in range(5):
     365   ...    squares.append(lambda: x**2)
     366
     367This gives you a list that contains 5 lambdas that calculate ``x**2``.  You
     368might expect that, when called, they would return, respectively, ``0``, ``1``,
     369``4``, ``9``, and ``16``.  However, when you actually try you will see that
     370they all return ``16``::
     371
     372   >>> squares[2]()
     373   16
     374   >>> squares[4]()
     375   16
     376
     377This happens because ``x`` is not local to the lambdas, but is defined in
     378the outer scope, and it is accessed when the lambda is called --- not when it
     379is defined.  At the end of the loop, the value of ``x`` is ``4``, so all the
     380functions now return ``4**2``, i.e. ``16``.  You can also verify this by
     381changing the value of ``x`` and see how the results of the lambdas change::
     382
     383   >>> x = 8
     384   >>> squares[2]()
     385   64
     386
     387In order to avoid this, you need to save the values in variables local to the
     388lambdas, so that they don't rely on the value of the global ``x``::
     389
     390   >>> squares = []
     391   >>> for x in range(5):
     392   ...    squares.append(lambda n=x: n**2)
     393
     394Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
     395when the lambda is defined so that it has the same value that ``x`` had at
     396that point in the loop.  This means that the value of ``n`` will be ``0``
     397in the first lambda, ``1`` in the second, ``2`` in the third, and so on.
     398Therefore each lambda will now return the correct result::
     399
     400   >>> squares[2]()
     401   4
     402   >>> squares[4]()
     403   16
     404
     405Note that this behaviour is not peculiar to lambdas, but applies to regular
     406functions too.
     407
     408
    372409How do I share global variables across modules?
    373410------------------------------------------------
     
    413450It's good practice if you import modules in the following order:
    414451
    415 1. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``)
     4521. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
    4164532. third-party library modules (anything installed in Python's site-packages
    417454   directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
     
    422459write ``import m2``, even though it's legal.  Write ``from package.sub import
    423460m2`` instead.  Relative imports can lead to a module being initialized twice,
    424 leading to confusing bugs.
     461leading to confusing bugs.  See :pep:`328` for details.
    425462
    426463It is sometimes necessary to move imports to a function or class to avoid
     
    487524
    488525
     526.. index::
     527   single: argument; difference from parameter
     528   single: parameter; difference from argument
     529
     530.. _faq-argument-vs-parameter:
     531
     532What is the difference between arguments and parameters?
     533--------------------------------------------------------
     534
     535:term:`Parameters <parameter>` are defined by the names that appear in a
     536function definition, whereas :term:`arguments <argument>` are the values
     537actually passed to a function when calling it.  Parameters define what types of
     538arguments a function can accept.  For example, given the function definition::
     539
     540   def func(foo, bar=None, **kwargs):
     541       pass
     542
     543*foo*, *bar* and *kwargs* are parameters of ``func``.  However, when calling
     544``func``, for example::
     545
     546   func(42, bar=314, extra=somevar)
     547
     548the values ``42``, ``314``, and ``somevar`` are arguments.
     549
     550
    489551How do I write a function with output parameters (call by reference)?
    490552---------------------------------------------------------------------
     
    650712   b = a
    651713   print b
    652    <__main__.A instance at 016D07CC>
     714   <__main__.A instance at 0x16D07CC>
    653715   print a
    654    <__main__.A instance at 016D07CC>
     716   <__main__.A instance at 0x16D07CC>
    655717
    656718Arguably the class has a name: even though it is bound to two names and invoked
     
    682744
    683745    >>> "a" in "b", "a"
    684     (False, '1')
     746    (False, 'a')
    685747
    686748Since the comma is not an operator, but a separator between expressions the
    687749above is evaluated as if you had entered::
    688750
    689     >>> ("a" in "b"), "a"
     751    ("a" in "b"), "a"
    690752
    691753not::
    692754
    693     >>> "a" in ("5", "a")
     755    "a" in ("b", "a")
    694756
    695757The same is true of the various assignment operators (``=``, ``+=`` etc).  They
     
    709771
    710772For versions previous to 2.5 the answer would be 'No'.
    711 
    712 .. XXX remove rest?
    713 
    714 In many cases you can mimic ``a ? b : c`` with ``a and b or c``, but there's a
    715 flaw: if *b* is zero (or empty, or ``None`` -- anything that tests false) then
    716 *c* will be selected instead.  In many cases you can prove by looking at the
    717 code that this can't happen (e.g. because *b* is a constant or has a type that
    718 can never be false), but in general this can be a problem.
    719 
    720 Tim Peters (who wishes it was Steve Majewski) suggested the following solution:
    721 ``(a and [b] or [c])[0]``.  Because ``[b]`` is a singleton list it is never
    722 false, so the wrong path is never taken; then applying ``[0]`` to the whole
    723 thing gets the *b* or *c* that you really wanted.  Ugly, but it gets you there
    724 in the rare cases where it is really inconvenient to rewrite your code using
    725 'if'.
    726 
    727 The best course is usually to write a simple ``if...else`` statement.  Another
    728 solution is to implement the ``?:`` operator as a function::
    729 
    730    def q(cond, on_true, on_false):
    731        if cond:
    732            if not isfunction(on_true):
    733                return on_true
    734            else:
    735                return apply(on_true)
    736        else:
    737            if not isfunction(on_false):
    738                return on_false
    739            else:
    740                return apply(on_false)
    741 
    742 In most cases you'll pass b and c directly: ``q(a, b, c)``.  To avoid evaluating
    743 b or c when they shouldn't be, encapsulate them within a lambda function, e.g.:
    744 ``q(a, lambda: b, lambda: c)``.
    745 
    746 It has been asked *why* Python has no if-then-else expression.  There are
    747 several answers: many languages do just fine without one; it can easily lead to
    748 less readable code; no sufficiently "Pythonic" syntax has been discovered; a
    749 search of the standard library found remarkably few places where using an
    750 if-then-else expression would make the code more understandable.
    751 
    752 In 2002, :pep:`308` was written proposing several possible syntaxes and the
    753 community was asked to vote on the issue.  The vote was inconclusive.  Most
    754 people liked one of the syntaxes, but also hated other syntaxes; many votes
    755 implied that people preferred no ternary operator rather than having a syntax
    756 they hated.
    757773
    758774
     
    768784
    769785   # First 10 Fibonacci numbers
    770    print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
     786   print map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1: f(x,f),
    771787   range(10))
    772788
     
    794810------------------------------------------------
    795811
    796 To specify an octal digit, precede the octal value with a zero.  For example, to
    797 set the variable "a" to the octal value "10" (8 in decimal), type::
    798 
    799    >>> a = 010
     812To specify an octal digit, precede the octal value with a zero, and then a lower
     813or uppercase "o".  For example, to set the variable "a" to the octal value "10"
     814(8 in decimal), type::
     815
     816   >>> a = 0o10
    800817   >>> a
    801818   8
     
    813830
    814831
    815 Why does -22 / 10 return -3?
    816 ----------------------------
     832Why does -22 // 10 return -3?
     833-----------------------------
    817834
    818835It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
    819836If you want that, and also want::
    820837
    821     i == (i / j) * j + (i % j)
     838    i == (i // j) * j + (i % j)
    822839
    823840then integer division has to return the floor.  C also requires that identity to
    824 hold, and then compilers that truncate ``i / j`` need to make ``i % j`` have the
    825 same sign as ``i``.
     841hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
     842the same sign as ``i``.
    826843
    827844There are few real use cases for ``i % j`` when ``j`` is negative.  When ``j``
     
    830847ago?  ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
    831848bite.
     849
     850.. note::
     851
     852   On Python 2, ``a / b`` returns the same as ``a // b`` if
     853   ``__future__.division`` is not in effect.  This is also known as "classic"
     854   division.
    832855
    833856
     
    862885To convert, e.g., the number 144 to the string '144', use the built-in type
    863886constructor :func:`str`.  If you want a hexadecimal or octal representation, use
    864 the built-in functions ``hex()`` or ``oct()``.  For fancy formatting, use
    865 :ref:`the % operator <string-formatting>` on strings, e.g. ``"%04d" % 144``
    866 yields ``'0144'`` and ``"%.3f" % (1/3.0)`` yields ``'0.333'``.  See the library
    867 reference manual for details.
     887the built-in functions :func:`hex` or :func:`oct`.  For fancy formatting, see
     888the :ref:`formatstrings` section, e.g. ``"{:04d}".format(144)`` yields
     889``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``.  You may also use
     890:ref:`the % operator <string-formatting>` on strings.  See the library reference
     891manual for details.
    868892
    869893
     
    874898ability, try converting the string to a list or use the array module::
    875899
     900   >>> import io
    876901   >>> s = "Hello, world"
    877902   >>> a = list(s)
     
    887912   array('c', 'Hello, world')
    888913   >>> a[0] = 'y' ; print a
    889    array('c', 'yello world')
     914   array('c', 'yello, world')
    890915   >>> a.tostring()
    891916   'yello, world'
     
    954979
    955980Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all
    956 occurences of any line terminator from the end of the string ``S`` without
     981occurrences of any line terminator from the end of the string ``S`` without
    957982removing other trailing whitespace.  If the string ``S`` represents more than
    958983one line, with several empty lines at the end, the line terminators for all the
     
    963988   ...          "\r\n")
    964989   >>> lines.rstrip("\n\r")
    965    "line 1 "
     990   'line 1 '
    966991
    967992Since this is typically only desired when reading text one line at a time, using
    968993``S.rstrip()`` this way works well.
    969994
    970 For older versions of Python, There are two partial substitutes:
     995For older versions of Python, there are two partial substitutes:
    971996
    972997- If you want to remove all trailing whitespace, use the ``rstrip()`` method of
     
    9891014if the line uses something other than whitespace as a separator.
    9901015
    991 For more complicated input parsing, regular expressions more powerful than C's
    992 :cfunc:`sscanf` and better suited for the task.
     1016For more complicated input parsing, regular expressions are more powerful
     1017than C's :c:func:`sscanf` and better suited for the task.
    9931018
    9941019
     
    10941119list, deleting duplicates as you go::
    10951120
    1096    if List:
    1097        List.sort()
    1098        last = List[-1]
    1099        for i in range(len(List)-2, -1, -1):
    1100            if last == List[i]:
    1101                del List[i]
     1121   if mylist:
     1122       mylist.sort()
     1123       last = mylist[-1]
     1124       for i in range(len(mylist)-2, -1, -1):
     1125           if last == mylist[i]:
     1126               del mylist[i]
    11021127           else:
    1103                last = List[i]
     1128               last = mylist[i]
    11041129
    11051130If all elements of the list may be used as dictionary keys (i.e. they are all
     
    11071132
    11081133   d = {}
    1109    for x in List:
    1110        d[x] = x
    1111    List = d.values()
     1134   for x in mylist:
     1135       d[x] = 1
     1136   mylist = list(d.keys())
    11121137
    11131138In Python 2.5 and later, the following is possible instead::
    11141139
    1115    List = list(set(List))
     1140   mylist = list(set(mylist))
    11161141
    11171142This converts the list into a set, thereby removing duplicates, and then back
     
    11491174You probably tried to make a multidimensional array like this::
    11501175
    1151    A = [[None] * 2] * 3
     1176   >>> A = [[None] * 2] * 3
    11521177
    11531178This looks correct if you print it::
     
    11811206
    11821207Or, you can use an extension that provides a matrix datatype; `Numeric Python
    1183 <http://numpy.scipy.org/>`_ is the best known.
     1208<http://www.numpy.org/>`_ is the best known.
    11841209
    11851210
     
    11891214Use a list comprehension::
    11901215
    1191    result = [obj.method() for obj in List]
     1216   result = [obj.method() for obj in mylist]
    11921217
    11931218More generically, you can try the following function::
     
    12001225
    12011226
     1227Why does a_tuple[i] += ['item'] raise an exception when the addition works?
     1228---------------------------------------------------------------------------
     1229
     1230This is because of a combination of the fact that augmented assignment
     1231operators are *assignment* operators, and the difference between mutable and
     1232immutable objects in Python.
     1233
     1234This discussion applies in general when augmented assignment operators are
     1235applied to elements of a tuple that point to mutable objects, but we'll use
     1236a ``list`` and ``+=`` as our exemplar.
     1237
     1238If you wrote::
     1239
     1240   >>> a_tuple = (1, 2)
     1241   >>> a_tuple[0] += 1
     1242   Traceback (most recent call last):
     1243      ...
     1244   TypeError: 'tuple' object does not support item assignment
     1245
     1246The reason for the exception should be immediately clear: ``1`` is added to the
     1247object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
     1248but when we attempt to assign the result of the computation, ``2``, to element
     1249``0`` of the tuple, we get an error because we can't change what an element of
     1250a tuple points to.
     1251
     1252Under the covers, what this augmented assignment statement is doing is
     1253approximately this::
     1254
     1255   >>> result = a_tuple[0] + 1
     1256   >>> a_tuple[0] = result
     1257   Traceback (most recent call last):
     1258     ...
     1259   TypeError: 'tuple' object does not support item assignment
     1260
     1261It is the assignment part of the operation that produces the error, since a
     1262tuple is immutable.
     1263
     1264When you write something like::
     1265
     1266   >>> a_tuple = (['foo'], 'bar')
     1267   >>> a_tuple[0] += ['item']
     1268   Traceback (most recent call last):
     1269     ...
     1270   TypeError: 'tuple' object does not support item assignment
     1271
     1272The exception is a bit more surprising, and even more surprising is the fact
     1273that even though there was an error, the append worked::
     1274
     1275    >>> a_tuple[0]
     1276    ['foo', 'item']
     1277
     1278To see why this happens, you need to know that (a) if an object implements an
     1279``__iadd__`` magic method, it gets called when the ``+=`` augmented assignment
     1280is executed, and its return value is what gets used in the assignment statement;
     1281and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list
     1282and returning the list.  That's why we say that for lists, ``+=`` is a
     1283"shorthand" for ``list.extend``::
     1284
     1285    >>> a_list = []
     1286    >>> a_list += [1]
     1287    >>> a_list
     1288    [1]
     1289
     1290This is equivalent to::
     1291
     1292    >>> result = a_list.__iadd__([1])
     1293    >>> a_list = result
     1294
     1295The object pointed to by a_list has been mutated, and the pointer to the
     1296mutated object is assigned back to ``a_list``.  The end result of the
     1297assignment is a no-op, since it is a pointer to the same object that ``a_list``
     1298was previously pointing to, but the assignment still happens.
     1299
     1300Thus, in our tuple example what is happening is equivalent to::
     1301
     1302   >>> result = a_tuple[0].__iadd__(['item'])
     1303   >>> a_tuple[0] = result
     1304   Traceback (most recent call last):
     1305     ...
     1306   TypeError: 'tuple' object does not support item assignment
     1307
     1308The ``__iadd__`` succeeds, and thus the list is extended, but even though
     1309``result`` points to the same object that ``a_tuple[0]`` already points to,
     1310that final assignment still results in an error, because tuples are immutable.
     1311
     1312
    12021313Dictionaries
    12031314============
     
    12141325be presented in order sorted by the key.
    12151326
    1216 A more complicated solution is to subclass ``UserDict.UserDict`` to create a
     1327A more complicated solution is to subclass ``dict`` to create a
    12171328``SortedDict`` class that prints itself in a predictable order.  Here's one
    12181329simpleminded implementation of such a class::
    12191330
    1220    import UserDict, string
    1221 
    1222    class SortedDict(UserDict.UserDict):
     1331   class SortedDict(dict):
    12231332       def __repr__(self):
    1224            result = []
    1225            append = result.append
    1226            keys = self.data.keys()
    1227            keys.sort()
    1228            for k in keys:
    1229                append("%s: %s" % (`k`, `self.data[k]`))
    1230            return "{%s}" % string.join(result, ", ")
    1231 
    1232      __str__ = __repr__
     1333           keys = sorted(self.keys())
     1334           result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
     1335           return "{{{}}}".format(", ".join(result))
     1336
     1337       __str__ = __repr__
    12331338
    12341339This will work for many common situations you might encounter, though it's far
     
    12521357strings by their uppercase values::
    12531358
    1254   tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform
     1359  tmp1 = [(x.upper(), x) for x in L]  # Schwartzian transform
    12551360  tmp1.sort()
    12561361  Usorted = [x[1] for x in tmp1]
     
    12591364each string::
    12601365
    1261   tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform
     1366  tmp2 = [(int(s[10:15]), s) for s in L]  # Schwartzian transform
    12621367  tmp2.sort()
    12631368  Isorted = [x[1] for x in tmp2]
     
    12961401An alternative for the last step is::
    12971402
    1298    result = []
    1299    for p in pairs: result.append(p[1])
     1403   >>> result = []
     1404   >>> for p in pairs: result.append(p[1])
    13001405
    13011406If you find this more legible, you might prefer to use this instead of the final
     
    13651470that does something::
    13661471
    1367    def search (obj):
     1472   def search(obj):
    13681473       if isinstance(obj, Mailbox):
    13691474           # ... code to search a mailbox
     
    14681573-----------------------------------------------------------
    14691574
    1470 Static data (in the sense of C++ or Java) is easy; static methods (again in the
    1471 sense of C++ or Java) are not supported directly.
     1575Both static data and static methods (in the sense of C++ or Java) are supported
     1576in Python.
    14721577
    14731578For static data, simply define a class attribute.  To assign a new value to the
     
    14881593
    14891594Caution: within a method of C, an assignment like ``self.count = 42`` creates a
    1490 new and unrelated instance vrbl named "count" in ``self``'s own dict.  Rebinding
    1491 of a class-static data name must always specify the class whether inside a
    1492 method or not::
     1595new and unrelated instance named "count" in ``self``'s own dict.  Rebinding of a
     1596class-static data name must always specify the class whether inside a method or
     1597not::
    14931598
    14941599   C.count = 314
     
    16201725
    16211726
     1727Why does the result of ``id()`` appear to be not unique?
     1728--------------------------------------------------------
     1729
     1730The :func:`id` builtin returns an integer that is guaranteed to be unique during
     1731the lifetime of the object.  Since in CPython, this is the object's memory
     1732address, it happens frequently that after an object is deleted from memory, the
     1733next freshly created object is allocated at the same position in memory.  This
     1734is illustrated by this example:
     1735
     1736>>> id(1000)
     173713901272
     1738>>> id(2000)
     173913901272
     1740
     1741The two ids belong to different integer objects that are created before, and
     1742deleted immediately after execution of the ``id()`` call.  To be sure that
     1743objects whose id you want to examine are still alive, create another reference
     1744to the object:
     1745
     1746>>> a = 1000; b = 2000
     1747>>> id(a)
     174813901272
     1749>>> id(b)
     175013891296
     1751
     1752
    16221753Modules
    16231754=======
     
    16371768directory.
    16381769
    1639 Running Python on a top level script is not considered an import and no ``.pyc``
    1640 will be created.  For example, if you have a top-level module ``abc.py`` that
    1641 imports another module ``xyz.py``, when you run abc, ``xyz.pyc`` will be created
    1642 since xyz is imported, but no ``abc.pyc`` file will be created since ``abc.py``
    1643 isn't being imported.
    1644 
    1645 If you need to create abc.pyc -- that is, to create a .pyc file for a module
     1770Running Python on a top level script is not considered an import and no
     1771``.pyc`` will be created.  For example, if you have a top-level module
     1772``foo.py`` that imports another module ``xyz.py``, when you run ``foo``,
     1773``xyz.pyc`` will be created since ``xyz`` is imported, but no ``foo.pyc`` file
     1774will be created since ``foo.py`` isn't being imported.
     1775
     1776If you need to create ``foo.pyc`` -- that is, to create a ``.pyc`` file for a module
    16461777that is not imported -- you can, using the :mod:`py_compile` and
    16471778:mod:`compileall` modules.
     
    16511782
    16521783   >>> import py_compile
    1653    >>> py_compile.compile('abc.py')
    1654 
    1655 This will write the ``.pyc`` to the same location as ``abc.py`` (or you can
     1784   >>> py_compile.compile('foo.py')                 # doctest: +SKIP
     1785
     1786This will write the ``.pyc`` to the same location as ``foo.py`` (or you can
    16561787override that with the optional parameter ``cfile``).
    16571788
  • python/vendor/current/Doc/faq/windows.rst

    r2 r388  
    77=====================
    88
    9 .. contents::
     9.. only:: html
     10
     11   .. contents::
    1012
    1113How do I run a Python program under Windows?
     
    1416This is not necessarily a straightforward question. If you are already familiar
    1517with running programs from the Windows command line then everything will seem
    16 obvious; otherwise, you might need a little more guidance.  There are also
    17 differences between Windows 95, 98, NT, ME, 2000 and XP which can add to the
    18 confusion.
     18obvious; otherwise, you might need a little more guidance.
    1919
    2020.. sidebar:: |Python Development on XP|_
     
    3333*typing* Windows commands into what is variously referred to as a "DOS window"
    3434or "Command prompt window".  Usually you can create such a window from your
    35 Start menu; under Windows 2000 the menu selection is :menuselection:`Start -->
     35Start menu; under Windows 7 the menu selection is :menuselection:`Start -->
    3636Programs --> Accessories --> Command Prompt`.  You should be able to recognize
    3737when you have started such a window because you will see a Windows "command
     
    4343might just as easily see something like::
    4444
    45    D:\Steve\Projects\Python>
     45   D:\YourName\Projects\Python>
    4646
    4747depending on how your computer has been set up and what else you have recently
     
    5050
    5151You need to realize that your Python scripts have to be processed by another
    52 program called the Python interpreter.  The interpreter reads your script,
     52program called the Python *interpreter*.  The interpreter reads your script,
    5353compiles it into bytecodes, and then executes the bytecodes to run your
    5454program. So, how do you arrange for the interpreter to handle your Python?
     
    5757"python" as an instruction to start the interpreter.  If you have opened a
    5858command window, you should try entering the command ``python`` and hitting
    59 return.  You should then see something like::
    60 
    61    Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
     59return.::
     60
     61   C:\Users\YourName> python
     62
     63You should then see something like::
     64
     65   Python 2.7.3 (default, Apr 10 2012, 22.71:26) [MSC v.1500 32 bit (Intel)] on win32
    6266   Type "help", "copyright", "credits" or "license" for more information.
    6367   >>>
     
    7983
    8084You may also find that you have a Start-menu entry such as :menuselection:`Start
    81 --> Programs --> Python 2.2 --> Python (command line)` that results in you
     85--> Programs --> Python 2.7 --> Python (command line)` that results in you
    8286seeing the ``>>>`` prompt in a new window.  If so, the window will disappear
    8387after you enter the Ctrl-Z character; Windows is running a single "python"
     
    8791gives you a message like::
    8892
    89    'python' is not recognized as an internal or external command,
    90    operable program or batch file.
     93   'python' is not recognized as an internal or external command, operable program or batch file.
    9194
    9295.. sidebar:: |Adding Python to DOS Path|_
     
    117120
    118121will probably tell you where it is installed; the usual location is something
    119 like ``C:\Python23``.  Otherwise you will be reduced to a search of your whole
     122like ``C:\Python27``.  Otherwise you will be reduced to a search of your whole
    120123disk ... use :menuselection:`Tools --> Find` or hit the :guilabel:`Search`
    121124button and look for "python.exe".  Supposing you discover that Python is
    122 installed in the ``C:\Python23`` directory (the default at the time of writing),
     125installed in the ``C:\Python27`` directory (the default at the time of writing),
    123126you should make sure that entering the command ::
    124127
    125    c:\Python23\python
     128   c:\Python27\python
    126129
    127130starts up the interpreter as above (and don't forget you'll need a "CTRL-Z" and
    128 an "Enter" to get out of it). Once you have verified the directory, you need to
    129 add it to the start-up routines your computer goes through.  For older versions
    130 of Windows the easiest way to do this is to edit the ``C:\AUTOEXEC.BAT``
    131 file. You would want to add a line like the following to ``AUTOEXEC.BAT``::
    132 
    133    PATH C:\Python23;%PATH%
    134 
    135 For Windows NT, 2000 and (I assume) XP, you will need to add a string such as ::
    136 
    137    ;C:\Python23
    138 
    139 to the current setting for the PATH environment variable, which you will find in
    140 the properties window of "My Computer" under the "Advanced" tab.  Note that if
    141 you have sufficient privilege you might get a choice of installing the settings
    142 either for the Current User or for System.  The latter is preferred if you want
    143 everybody to be able to run Python on the machine.
    144 
    145 If you aren't confident doing any of these manipulations yourself, ask for help!
    146 At this stage you may want to reboot your system to make absolutely sure the new
    147 setting has taken effect.  You probably won't need to reboot for Windows NT, XP
    148 or 2000.  You can also avoid it in earlier versions by editing the file
    149 ``C:\WINDOWS\COMMAND\CMDINIT.BAT`` instead of ``AUTOEXEC.BAT``.
    150 
    151 You should now be able to start a new command window, enter ``python`` at the
    152 ``C:\>`` (or whatever) prompt, and see the ``>>>`` prompt that indicates the
    153 Python interpreter is reading interactive commands.
    154 
    155 Let's suppose you have a program called ``pytest.py`` in directory
    156 ``C:\Steve\Projects\Python``.  A session to run that program might look like
    157 this::
    158 
    159    C:\> cd \Steve\Projects\Python
    160    C:\Steve\Projects\Python> python pytest.py
    161 
    162 Because you added a file name to the command to start the interpreter, when it
    163 starts up it reads the Python script in the named file, compiles it, executes
    164 it, and terminates, so you see another ``C:\>`` prompt.  You might also have
    165 entered ::
    166 
    167    C:\> python \Steve\Projects\Python\pytest.py
    168 
    169 if you hadn't wanted to change your current directory.
    170 
    171 Under NT, 2000 and XP you may well find that the installation process has also
    172 arranged that the command ``pytest.py`` (or, if the file isn't in the current
    173 directory, ``C:\Steve\Projects\Python\pytest.py``) will automatically recognize
    174 the ".py" extension and run the Python interpreter on the named file. Using this
    175 feature is fine, but *some* versions of Windows have bugs which mean that this
    176 form isn't exactly equivalent to using the interpreter explicitly, so be
    177 careful.
    178 
    179 The important things to remember are:
    180 
    181 1. Start Python from the Start Menu, or make sure the PATH is set correctly so
    182    Windows can find the Python interpreter. ::
    183 
    184       python
    185 
    186    should give you a '>>>' prompt from the Python interpreter. Don't forget the
    187    CTRL-Z and ENTER to terminate the interpreter (and, if you started the window
    188    from the Start Menu, make the window disappear).
    189 
    190 2. Once this works, you run programs with commands::
    191 
    192       python {program-file}
    193 
    194 3. When you know the commands to use you can build Windows shortcuts to run the
    195    Python interpreter on any of your scripts, naming particular working
    196    directories, and adding them to your menus.  Take a look at ::
    197 
    198       python --help
    199 
    200    if your needs are complex.
    201 
    202 4. Interactive mode (where you see the ``>>>`` prompt) is best used for checking
    203    that individual statements and expressions do what you think they will, and
    204    for developing code by experiment.
    205 
     131an "Enter" to get out of it). Once you have verified the directory, you can
     132add it to the system path to make it easier to start Python by just running
     133the ``python`` command. This is currently an option in the installer as of
     134CPython 2.7.
     135
     136More information about environment variables can be found on the
     137:ref:`Using Python on Windows <setting-envvars>` page.
    206138
    207139How do I make Python scripts executable?
    208140----------------------------------------
    209141
    210 On Windows 2000, the standard Python installer already associates the .py
     142On Windows, the standard Python installer already associates the .py
    211143extension with a file type (Python.File) and gives that file type an open
    212144command that runs the interpreter (``D:\Program Files\Python\python.exe "%1"
     
    214146'foo.py'.  If you'd rather be able to execute the script by simple typing 'foo'
    215147with no extension you need to add .py to the PATHEXT environment variable.
    216 
    217 On Windows NT, the steps taken by the installer as described above allow you to
    218 run a script with 'foo.py', but a longtime bug in the NT command processor
    219 prevents you from redirecting the input or output of any script executed in this
    220 way.  This is often important.
    221 
    222 The incantation for making a Python script executable under WinNT is to give the
    223 file an extension of .cmd and add the following as the first line::
    224 
    225    @setlocal enableextensions & python -x %~f0 %* & goto :EOF
    226 
    227148
    228149Why does Python sometimes take so long to start?
     
    243164
    244165
    245 Where is Freeze for Windows?
    246 ----------------------------
    247 
    248 "Freeze" is a program that allows you to ship a Python program as a single
    249 stand-alone executable file.  It is *not* a compiler; your programs don't run
    250 any faster, but they are more easily distributable, at least to platforms with
    251 the same OS and CPU.  Read the README file of the freeze program for more
    252 disclaimers.
    253 
    254 You can use freeze on Windows, but you must download the source tree (see
    255 http://www.python.org/download/source).  The freeze program is in the
    256 ``Tools\freeze`` subdirectory of the source tree.
    257 
    258 You need the Microsoft VC++ compiler, and you probably need to build Python.
    259 The required project files are in the PCbuild directory.
    260 
     166How do I make an executable from a Python script?
     167-------------------------------------------------
     168
     169See http://www.py2exe.org/ for a distutils extension that allows you
     170to create console and GUI executables from Python code.
    261171
    262172Is a ``*.pyd`` file the same as a DLL?
     
    2871971. Do _not_ build Python into your .exe file directly.  On Windows, Python must
    288198   be a DLL to handle importing modules that are themselves DLL's.  (This is the
    289    first key undocumented fact.) Instead, link to :file:`python{NN}.dll`; it is
    290    typically installed in ``C:\Windows\System``.  NN is the Python version, a
    291    number such as "23" for Python 2.3.
    292 
    293    You can link to Python statically or dynamically.  Linking statically means
    294    linking against :file:`python{NN}.lib`, while dynamically linking means
    295    linking against :file:`python{NN}.dll`.  The drawback to dynamic linking is
    296    that your app won't run if :file:`python{NN}.dll` does not exist on your
    297    system.  (General note: :file:`python{NN}.lib` is the so-called "import lib"
    298    corresponding to :file:`python.dll`.  It merely defines symbols for the
    299    linker.)
    300 
    301    Linking dynamically greatly simplifies link options; everything happens at
    302    run time.  Your code must load :file:`python{NN}.dll` using the Windows
     199   first key undocumented fact.)  Instead, link to :file:`python{NN}.dll`; it is
     200   typically installed in ``C:\Windows\System``.  *NN* is the Python version, a
     201   number such as "27" for Python 2.7.
     202
     203   You can link to Python in two different ways.  Load-time linking means
     204   linking against :file:`python{NN}.lib`, while run-time linking means linking
     205   against :file:`python{NN}.dll`.  (General note: :file:`python{NN}.lib` is the
     206   so-called "import lib" corresponding to :file:`python{NN}.dll`.  It merely
     207   defines symbols for the linker.)
     208
     209   Run-time linking greatly simplifies link options; everything happens at run
     210   time.  Your code must load :file:`python{NN}.dll` using the Windows
    303211   ``LoadLibraryEx()`` routine.  The code must also use access routines and data
    304212   in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained
     
    308216   Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe
    309217   first.
     218
     219   .. XXX what about static linking?
    310220
    3112212. If you use SWIG, it is easy to create a Python "extension module" that will
     
    373283   (defined in your extension module) that contains read() and write() methods.
    374284
    375 
    376 How do I use Python for CGI?
    377 ----------------------------
    378 
    379 On the Microsoft IIS server or on the Win95 MS Personal Web Server you set up
    380 Python in the same way that you would set up any other scripting engine.
    381 
    382 Run regedt32 and go to::
    383 
    384     HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ScriptMap
    385 
    386 and enter the following line (making any specific changes that your system may
    387 need)::
    388 
    389     .py :REG_SZ: c:\<path to python>\python.exe -u %s %s
    390 
    391 This line will allow you to call your script with a simple reference like:
    392 ``http://yourserver/scripts/yourscript.py`` provided "scripts" is an
    393 "executable" directory for your server (which it usually is by default).  The
    394 :option:`-u` flag specifies unbuffered and binary mode for stdin - needed when
    395 working with binary data.
    396 
    397 In addition, it is recommended that using ".py" may not be a good idea for the
    398 file extensions when used in this context (you might want to reserve ``*.py``
    399 for support modules and use ``*.cgi`` or ``*.cgp`` for "main program" scripts).
    400 
    401 In order to set up Internet Information Services 5 to use Python for CGI
    402 processing, please see the following links:
    403 
    404    http://www.e-coli.net/pyiis_server.html (for Win2k Server)
    405    http://www.e-coli.net/pyiis.html (for Win2k pro)
    406 
    407 Configuring Apache is much simpler.  In the Apache configuration file
    408 ``httpd.conf``, add the following line at the end of the file::
    409 
    410     ScriptInterpreterSource Registry
    411 
    412 Then, give your Python CGI-scripts the extension .py and put them in the cgi-bin
    413 directory.
    414 
    415 
    416285How do I keep editors from inserting tabs into my Python source?
    417286----------------------------------------------------------------
     
    442311--------------------------------------
    443312
    444 Use win32api::
     313Prior to Python 2.7 and 3.2, to terminate a process, you can use :mod:`ctypes`::
     314
     315   import ctypes
    445316
    446317   def kill(pid):
    447318       """kill function for Win32"""
    448        import win32api
    449        handle = win32api.OpenProcess(1, 0, pid)
    450        return (0 != win32api.TerminateProcess(handle, 0))
    451 
    452 
    453 Why does os.path.isdir() fail on NT shared directories?
    454 -------------------------------------------------------
    455 
    456 The solution appears to be always append the "\\" on the end of shared
    457 drives.
    458 
    459    >>> import os
    460    >>> os.path.isdir( '\\\\rorschach\\public')
    461    0
    462    >>> os.path.isdir( '\\\\rorschach\\public\\')
    463    1
    464 
    465 It helps to think of share points as being like drive letters.  Example::
    466 
    467    k: is not a directory
    468    k:\ is a directory
    469    k:\media is a directory
    470    k:\media\ is not a directory
    471 
    472 The same rules apply if you substitute "k:" with "\\conky\foo"::
    473 
    474    \\conky\foo  is not a directory
    475    \\conky\foo\ is a directory
    476    \\conky\foo\media is a directory
    477    \\conky\foo\media\ is not a directory
    478 
    479 
    480 cgi.py (or other CGI programming) doesn't work sometimes on NT or win95!
    481 ------------------------------------------------------------------------
    482 
    483 Be sure you have the latest python.exe, that you are using python.exe rather
    484 than a GUI version of Python and that you have configured the server to execute
    485 ::
    486 
    487    "...\python.exe -u ..."
    488 
    489 for the CGI execution.  The :option:`-u` (unbuffered) option on NT and Win95
    490 prevents the interpreter from altering newlines in the standard input and
    491 output.  Without it post/multipart requests will seem to have the wrong length
    492 and binary (e.g. GIF) responses may get garbled (resulting in broken images, PDF
    493 files, and other binary downloads failing).
    494 
    495 
    496 Why doesn't os.popen() work in PythonWin on NT?
    497 -----------------------------------------------
    498 
    499 The reason that os.popen() doesn't work from within PythonWin is due to a bug in
    500 Microsoft's C Runtime Library (CRT). The CRT assumes you have a Win32 console
    501 attached to the process.
    502 
    503 You should use the win32pipe module's popen() instead which doesn't depend on
    504 having an attached Win32 console.
    505 
    506 Example::
    507 
    508    import win32pipe
    509    f = win32pipe.popen('dir /c c:\\')
    510    print f.readlines()
    511    f.close()
    512 
    513 
    514 Why doesn't os.popen()/win32pipe.popen() work on Win9x?
    515 -------------------------------------------------------
    516 
    517 There is a bug in Win9x that prevents os.popen/win32pipe.popen* from
    518 working. The good news is there is a way to work around this problem.  The
    519 Microsoft Knowledge Base article that you need to lookup is: Q150956. You will
    520 find links to the knowledge base at: http://support.microsoft.com/.
    521 
    522 
    523 PyRun_SimpleFile() crashes on Windows but not on Unix; why?
    524 -----------------------------------------------------------
    525 
    526 This is very sensitive to the compiler vendor, version and (perhaps) even
    527 options.  If the FILE* structure in your embedding program isn't the same as is
    528 assumed by the Python interpreter it won't work.
    529 
    530 The Python 1.5.* DLLs (``python15.dll``) are all compiled with MS VC++ 5.0 and
    531 with multithreading-DLL options (``/MD``).
    532 
    533 If you can't change compilers or flags, try using :cfunc:`Py_RunSimpleString`.
    534 A trick to get it to run an arbitrary file is to construct a call to
    535 :func:`execfile` with the name of your file as argument.
    536 
    537 Also note that you can not mix-and-match Debug and Release versions.  If you
    538 wish to use the Debug Multithreaded DLL, then your module *must* have an "_d"
    539 appended to the base name.
    540 
    541 
    542 Importing _tkinter fails on Windows 95/98: why?
    543 ------------------------------------------------
    544 
    545 Sometimes, the import of _tkinter fails on Windows 95 or 98, complaining with a
    546 message like the following::
    547 
    548    ImportError: DLL load failed: One of the library files needed
    549    to run this application cannot be found.
    550 
    551 It could be that you haven't installed Tcl/Tk, but if you did install Tcl/Tk,
    552 and the Wish application works correctly, the problem may be that its installer
    553 didn't manage to edit the autoexec.bat file correctly.  It tries to add a
    554 statement that changes the PATH environment variable to include the Tcl/Tk 'bin'
    555 subdirectory, but sometimes this edit doesn't quite work.  Opening it with
    556 notepad usually reveals what the problem is.
    557 
    558 (One additional hint, noted by David Szafranski: you can't use long filenames
    559 here; e.g. use ``C:\PROGRA~1\Tcl\bin`` instead of ``C:\Program Files\Tcl\bin``.)
    560 
     319       kernel32 = ctypes.windll.kernel32
     320       handle = kernel32.OpenProcess(1, 0, pid)
     321       return (0 != kernel32.TerminateProcess(handle, 0))
     322
     323In 2.7 and 3.2, :func:`os.kill` is implemented similar to the above function,
     324with the additional feature of being able to send CTRL+C and CTRL+BREAK
     325to console subprocesses which are designed to handle those signals. See
     326:func:`os.kill` for further details.
    561327
    562328How do I extract the downloaded documentation on Windows?
     
    571337http://www.winzip.com.)
    572338
    573 
    574 Missing cw3215mt.dll (or missing cw3215.dll)
    575 --------------------------------------------
    576 
    577 Sometimes, when using Tkinter on Windows, you get an error that cw3215mt.dll or
    578 cw3215.dll is missing.
    579 
    580 Cause: you have an old Tcl/Tk DLL built with cygwin in your path (probably
    581 ``C:\Windows``).  You must use the Tcl/Tk DLLs from the standard Tcl/Tk
    582 installation (Python 1.5.2 comes with one).
    583 
    584 
    585 Warning about CTL3D32 version from installer
    586 --------------------------------------------
    587 
    588 The Python installer issues a warning like this::
    589 
    590    This version uses ``CTL3D32.DLL`` which is not the correct version.
    591    This version is used for windows NT applications only.
    592 
    593 Tim Peters:
    594 
    595    This is a Microsoft DLL, and a notorious source of problems.  The message
    596    means what it says: you have the wrong version of this DLL for your operating
    597    system.  The Python installation did not cause this -- something else you
    598    installed previous to this overwrote the DLL that came with your OS (probably
    599    older shareware of some sort, but there's no way to tell now).  If you search
    600    for "CTL3D32" using any search engine (AltaVista, for example), you'll find
    601    hundreds and hundreds of web pages complaining about the same problem with
    602    all sorts of installation programs.  They'll point you to ways to get the
    603    correct version reinstalled on your system (since Python doesn't cause this,
    604    we can't fix it).
    605 
    606 David A Burton has written a little program to fix this.  Go to
    607 http://www.burtonsys.com/downloads.html and click on "ctl3dfix.zip".
Note: See TracChangeset for help on using the changeset viewer.