Changeset 388 for python/vendor/current/Doc/faq
- Timestamp:
- Mar 19, 2014, 11:11:30 AM (11 years ago)
- Location:
- python/vendor/current/Doc/faq
- Files:
-
- 8 edited
Legend:
- Unmodified
- Added
- Removed
-
python/vendor/current/Doc/faq/design.rst
r2 r388 8 8 Guido van Rossum believes that using indentation for grouping is extremely 9 9 elegant and contributes a lot to the clarity of the average Python program. 10 Most people learn to love this feature after a while.10 Most people learn to love this feature after a while. 11 11 12 12 Since there are no begin/end brackets there cannot be a disagreement between … … 29 29 least slightly uneasy when reading (or being required to write) another style. 30 30 31 Many coding styles place begin/end brackets on a line by themsel f. This makes31 Many coding styles place begin/end brackets on a line by themselves. This makes 32 32 programs considerably longer and wastes valuable screen space, making it harder 33 33 to get a good overview of a program. Ideally, a function should fit on one … … 49 49 People are often very surprised by results like this:: 50 50 51 >>> 1.2 -1.051 >>> 1.2 - 1.0 52 52 0.199999999999999996 53 53 … … 76 76 that was probably intended:: 77 77 78 >>> 0.279 0.2000000000000000 180 >>> print 0.278 >>> 1.1 - 0.9 79 0.20000000000000007 80 >>> print 1.1 - 0.9 81 81 0.2 82 82 … … 86 86 numbers is less than a certain threshold:: 87 87 88 epsilon = 0.0000000000001 # Tiny allowed error88 epsilon = 0.0000000000001 # Tiny allowed error 89 89 expected_result = 0.4 90 90 … … 132 132 reference or call the method from a particular class. In C++, if you want to 133 133 use 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. 134 to use the ``::`` operator -- in Python you can write 135 ``baseclass.methodname(self, <argument list>)``. This is particularly useful 136 for :meth:`__init__` methods, and in general in cases where a derived class 137 method wants to extend the base class method of the same name and thus has to 138 call the base class method somehow. 138 139 139 140 Finally, for instance variables it solves a syntactic problem with assignment: 140 141 since 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 through142 value is assigned in a function body (and that aren't explicitly declared 143 global), there has to be some way to tell the interpreter that an assignment was 144 meant to assign to an instance variable instead of to a local variable, and it 145 should preferably be syntactic (for efficiency reasons). C++ does this through 145 146 declarations, 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"solves147 to introduce them just for this purpose. Using the explicit ``self.var`` solves 147 148 this 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 150 have to search the instance's directories. To put it another way, local 151 variables and instance variables live in two different namespaces, and you need 152 to tell Python which namespace to use. 152 153 153 154 … … 225 226 that didn't have methods at all (e.g. tuples). It is also convenient to have a 226 227 function that can readily be applied to an amorphous collection of objects when 227 you use the functional features of Python (``map()``, `` apply()`` et al).228 you use the functional features of Python (``map()``, ``zip()`` et al). 228 229 229 230 In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is … … 235 236 .. XXX talk about protocols? 236 237 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. 239 242 240 243 … … 295 298 ------------------------ 296 299 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:: 300 A try/except block is extremely efficient if no exceptions are raised. Actually 301 catching an exception is expensive. In versions of Python prior to 2.0 it was 302 common to use this idiom:: 299 303 300 304 try: 301 value = dict[key]305 value = mydict[key] 302 306 except KeyError: 303 dict[key] = getvalue(key)304 value = dict[key]307 mydict[key] = getvalue(key) 308 value = mydict[key] 305 309 306 310 This only made sense when you expected the dict to have the key almost all the 307 311 time. If that wasn't the case, you coded it like this:: 308 312 309 if dict.has_key(key):310 value = dict[key]313 if key in mydict: 314 value = mydict[key] 311 315 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))``. 317 322 318 323 … … 366 371 Answer 2: Fortunately, there is `Stackless Python <http://www.stackless.com>`_, 367 372 which 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 375 Why can't lambda expressions contain statements? 376 ------------------------------------------------ 377 378 Python lambda expressions cannot contain statements because Python's syntactic 377 379 framework can't handle statements nested inside expressions. However, in 378 380 Python, this is not a serious problem. Unlike lambda forms in other languages, … … 381 383 382 384 Functions are already first class objects in Python, and can be declared in a 383 local scope. Therefore the only advantage of using a lambda forminstead of a385 local scope. Therefore the only advantage of using a lambda instead of a 384 386 locally-defined function is that you don't need to invent a name for the 385 387 function -- but that's just a local variable to which the function object (which 386 is exactly the same type of object that a lambda formyields) is assigned!388 is exactly the same type of object that a lambda expression yields) is assigned! 387 389 388 390 … … 433 435 <http://pyinline.sourceforge.net/>`_, `Py2Cmod 434 436 <http://sourceforge.net/projects/py2cmod/>`_, and `Weave 435 <http://www.scipy.org/ site_content/weave>`_.437 <http://www.scipy.org/Weave>`_. 436 438 437 439 … … 451 453 the behavior of the reference counting implementation. 452 454 455 .. XXX relevant for Python 2.6? 456 453 457 Sometimes objects get stuck in tracebacks temporarily and hence are not 454 458 deallocated when you might expect. Clear the tracebacks with:: … … 462 466 handling of an exception (usually the most recent exception). 463 467 464 In the absence of circularities and tracebacks, Python programs need not465 explicitly manage memory.468 In the absence of circularities and tracebacks, Python programs do not need to 469 manage memory explicitly. 466 470 467 471 Why doesn't Python use a more traditional garbage collection scheme? For one … … 482 486 of file descriptors long before it runs out of memory:: 483 487 484 for file in <very long list of files>:488 for file in very_long_list_of_files: 485 489 f = open(file) 486 490 c = f.read(1) … … 489 493 to f closes the previous file. Using GC, this is not guaranteed. If you want 490 494 to 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()495 explicitly close the file or use the :keyword:`with` statement; this will work 496 regardless of GC:: 497 498 for file in very_long_list_of_files: 499 with open(file) as f: 500 c = f.read(1) 497 501 498 502 … … 590 594 construct a new list with the same value it won't be found; e.g.:: 591 595 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 the596 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 596 600 second line differs from that in the first line. In other words, dictionary 597 601 keys should be compared using ``==``, not using :keyword:`is`. … … 614 618 There is a trick to get around this if you need to, but use it at your own risk: 615 619 You 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 the620 :meth:`__eq__` and a :meth:`__hash__` method. You must then make sure that the 617 621 hash value for all such wrapper objects that reside in a dictionary (or other 618 622 hash based structure), remain fixed while the object is in the dictionary (or … … 622 626 def __init__(self, the_list): 623 627 self.the_list = the_list 624 def __ cmp__(self, other):628 def __eq__(self, other): 625 629 return self.the_list == other.the_list 626 630 def __hash__(self): 627 631 l = self.the_list 628 632 result = 98767 - len(l)*555 629 for i in range(len(l)):633 for i, el in enumerate(l): 630 634 try: 631 result = result + (hash( l[i]) % 9999999) * 1001 + i632 except :635 result = result + (hash(el) % 9999999) * 1001 + i 636 except Exception: 633 637 result = (result % 7777777) + i * 333 634 638 return result … … 638 642 overflow. 639 643 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__()``),644 Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__eq__(o2) 645 is True``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``), 642 646 regardless of whether the object is in a dictionary or not. If you fail to meet 643 647 these restrictions dictionaries and other hash based structures will misbehave. … … 663 667 order:: 664 668 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]... 667 671 668 672 … … 678 682 (ABCs). You can then use :func:`isinstance` and :func:`issubclass` to check 679 683 whether 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`. 682 687 683 688 For Python, many of the advantages of interface specifications can be obtained … … 713 718 This type of bug commonly bites neophyte programmers. Consider this function:: 714 719 715 def foo( D={}): # Danger: shared reference to one dict for all calls720 def foo(mydict={}): # Danger: shared reference to one dict for all calls 716 721 ... compute something ... 717 D[key] = value718 return D719 720 The first time you call this function, `` D`` contains a single item. The second721 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 725 The first time you call this function, ``mydict`` contains a single item. The 726 second time, ``mydict`` contains two items because when ``foo()`` begins 727 executing, ``mydict`` starts out with an item already in it. 723 728 724 729 It is often expected that a function call creates new objects for default … … 736 741 list/dictionary/whatever if it is. For example, don't write:: 737 742 738 def foo( dict={}):743 def foo(mydict={}): 739 744 ... 740 745 741 746 but:: 742 747 743 def foo( dict=None):744 if dict is None:745 dict = {}# create a new dict for local namespace748 def foo(mydict=None): 749 if mydict is None: 750 mydict = {} # create a new dict for local namespace 746 751 747 752 This feature can be useful. When you have a function that's time-consuming to … … 751 756 752 757 # Callers will never provide a third parameter for this function. 753 def expensive 754 if _cache.has_key((arg1, arg2)):758 def expensive(arg1, arg2, _cache={}): 759 if (arg1, arg2) in _cache: 755 760 return _cache[(arg1, arg2)] 756 761 … … 772 777 languages. For example:: 773 778 774 class label: pass # declare a label779 class label: pass # declare a label 775 780 776 781 try: 777 782 ... 778 if (condition): raise label()# goto label783 if condition: raise label() # goto label 779 784 ... 780 except label: # where to goto785 except label: # where to goto 781 786 pass 782 787 ... … … 803 808 accept forward slashes too:: 804 809 805 f = open("/mydir/file.txt") # works fine!810 f = open("/mydir/file.txt") # works fine! 806 811 807 812 If you're trying to build a pathname for a DOS command, try e.g. one of :: … … 820 825 821 826 with obj: 822 a = 1 # equivalent to obj.a = 1827 a = 1 # equivalent to obj.a = 1 823 828 total = total + 1 # obj.total = obj.total + 1 824 829 … … 851 856 volume) can, however, easily be achieved in Python by assignment. Instead of:: 852 857 853 function(args). dict[index][index].a = 21854 function(args). dict[index][index].b = 42855 function(args). dict[index][index].c = 63858 function(args).mydict[index][index].a = 21 859 function(args).mydict[index][index].b = 42 860 function(args).mydict[index][index].c = 63 856 861 857 862 write this:: 858 863 859 ref = function(args). dict[index][index]864 ref = function(args).mydict[index][index] 860 865 ref.a = 21 861 866 ref.b = 42 … … 864 869 This also has the side-effect of increasing execution speed because name 865 870 bindings 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. 871 to perform the resolution once. 868 872 869 873 … … 908 912 When you have a literal value for a list, tuple, or dictionary spread across 909 913 multiple 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 in911 your editorwithout creating a syntax error.914 remember to add a comma to the previous line. The lines can also be reordered 915 without creating a syntax error. 912 916 913 917 Accidentally omitting the comma can lead to errors that are hard to diagnose. -
python/vendor/current/Doc/faq/extending.rst
r2 r388 3 3 ======================= 4 4 5 .. contents:: 5 .. only:: html 6 7 .. contents:: 6 8 7 9 .. highlight:: c … … 26 28 C++ objects with constructors are probably not a good idea. 27 29 30 31 .. _c-wrapper-software: 28 32 29 33 Writing C is hard; are there any alternatives? … … 52 56 <http://cxx.sourceforge.net/>`_ `Boost 53 57 <http://www.boost.org/libs/python/doc/index.html>`_, or `Weave 54 <http://www.scipy.org/ site_content/weave>`_ are also alternatives for wrapping58 <http://www.scipy.org/Weave>`_ are also alternatives for wrapping 55 59 C++ libraries. 56 60 … … 59 63 ----------------------------------------------------- 60 64 61 The highest-level function to do this is :c func:`PyRun_SimpleString` which takes65 The highest-level function to do this is :c:func:`PyRun_SimpleString` which takes 62 66 a single string argument to be executed in the context of the module 63 67 ``__main__`` and returns 0 for success and -1 when an exception occurred 64 68 (including ``SyntaxError``). If you want more control, use 65 :c func:`PyRun_String`; see the source for :cfunc:`PyRun_SimpleString` in69 :c:func:`PyRun_String`; see the source for :c:func:`PyRun_SimpleString` in 66 70 ``Python/pythonrun.c``. 67 71 … … 70 74 --------------------------------------------------------- 71 75 72 Call the function :c func:`PyRun_String` from the previous question with the73 start symbol :c data:`Py_eval_input`; it parses an expression, evaluates it and76 Call the function :c:func:`PyRun_String` from the previous question with the 77 start symbol :c:data:`Py_eval_input`; it parses an expression, evaluates it and 74 78 returns its value. 75 79 … … 78 82 ----------------------------------------------- 79 83 80 That depends on the object's type. If it's a tuple, :c func:`PyTuple_Size`81 returns its length and :c func:`PyTuple_GetItem` returns the item at a specified82 index. Lists have similar functions, :c func:`PyListSize` and83 :c func:`PyList_GetItem`.84 85 For strings, :c func:`PyString_Size` returns its length and86 :c func:`PyString_AsString` a pointer to its value. Note that Python strings may87 contain null bytes so C's :c func:`strlen` should not be used.84 That depends on the object's type. If it's a tuple, :c:func:`PyTuple_Size` 85 returns its length and :c:func:`PyTuple_GetItem` returns the item at a specified 86 index. Lists have similar functions, :c:func:`PyListSize` and 87 :c:func:`PyList_GetItem`. 88 89 For strings, :c:func:`PyString_Size` returns its length and 90 :c:func:`PyString_AsString` a pointer to its value. Note that Python strings may 91 contain null bytes so C's :c:func:`strlen` should not be used. 88 92 89 93 To test the type of an object, first make sure it isn't *NULL*, and then use 90 :c func:`PyString_Check`, :cfunc:`PyTuple_Check`, :cfunc:`PyList_Check`, etc.94 :c:func:`PyString_Check`, :c:func:`PyTuple_Check`, :c:func:`PyList_Check`, etc. 91 95 92 96 There is also a high-level API to Python objects which is provided by the 93 97 so-called 'abstract' interface -- read ``Include/abstract.h`` for further 94 98 details. It allows interfacing with any kind of Python sequence using calls 95 like :c func:`PySequence_Length`, :cfunc:`PySequence_GetItem`, etc.) as well as99 like :c:func:`PySequence_Length`, :c:func:`PySequence_GetItem`, etc.) as well as 96 100 many other useful protocols. 97 101 … … 102 106 You can't. Use ``t = PyTuple_New(n)`` instead, and fill it with objects using 103 107 ``PyTuple_SetItem(t, i, o)`` -- note that this "eats" a reference count of 104 ``o``, so you have to :c func:`Py_INCREF` it. Lists have similar functions108 ``o``, so you have to :c:func:`Py_INCREF` it. Lists have similar functions 105 109 ``PyList_New(n)`` and ``PyList_SetItem(l, i, o)``. Note that you *must* set all 106 110 the tuple items to some value before you pass the tuple to Python code -- … … 111 115 ---------------------------------------- 112 116 113 The :c func:`PyObject_CallMethod` function can be used to call an arbitrary117 The :c:func:`PyObject_CallMethod` function can be used to call an arbitrary 114 118 method of an object. The parameters are the object, the name of the method to 115 call, a format string like that used with :c func:`Py_BuildValue`, and the119 call, a format string like that used with :c:func:`Py_BuildValue`, and the 116 120 argument values:: 117 121 … … 121 125 122 126 This works for any object that has methods -- whether built-in or user-defined. 123 You are responsible for eventually :c func:`Py_DECREF`\ 'ing the return value.127 You are responsible for eventually :c:func:`Py_DECREF`\ 'ing the return value. 124 128 125 129 To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the … … 134 138 } 135 139 136 Note that since :c func:`PyObject_CallObject` *always* wants a tuple for the140 Note that since :c:func:`PyObject_CallObject` *always* wants a tuple for the 137 141 argument list, to call a function without arguments, pass "()" for the format, 138 142 and to call a function with one argument, surround the argument in parentheses, … … 185 189 attr = PyObject_GetAttrString(module, "<attrname>"); 186 190 187 Calling :c func:`PyObject_SetAttrString` to assign to variables in the module191 Calling :c:func:`PyObject_SetAttrString` to assign to variables in the module 188 192 also works. 189 193 … … 198 202 Python type around a C structure (pointer) type will also work for C++ objects. 199 203 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>`_ 204 For C++ libraries, see :ref:`c-wrapper-software`. 205 205 206 206 … … 270 270 behavior sufficiently. IDLE uses this, for example. 271 271 272 The easiest way to do it in C is to call :c func:`PyRun_InteractiveLoop` (perhaps272 The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` (perhaps 273 273 in a separate thread) and let the Python interpreter handle the input for 274 you. You can also set the :c func:`PyOS_ReadlineFunctionPointer` to point at your274 you. You can also set the :c:func:`PyOS_ReadlineFunctionPointer` to point at your 275 275 custom input function. See ``Modules/readline.c`` and ``Parser/myreadline.c`` 276 276 for more hints. … … 278 278 However sometimes you have to run the embedded Python interpreter in the same 279 279 thread as your rest application and you can't allow the 280 :c func:`PyRun_InteractiveLoop` to stop while waiting for user input. The one281 solution then is to call :c func:`PyParser_ParseString` and test for ``e.error``280 :c:func:`PyRun_InteractiveLoop` to stop while waiting for user input. The one 281 solution then is to call :c:func:`PyParser_ParseString` and test for ``e.error`` 282 282 equal to ``E_EOF``, which means the input is incomplete). Here's a sample code 283 283 fragment, untested, inspired by code from Alex Farber:: … … 310 310 311 311 Another solution is trying to compile the received string with 312 :c func:`Py_CompileString`. If it compiles without errors, try to execute the313 returned code object by calling :c func:`PyEval_EvalCode`. Otherwise save the312 :c:func:`Py_CompileString`. If it compiles without errors, try to execute the 313 returned code object by calling :c:func:`PyEval_EvalCode`. Otherwise save the 314 314 input for later. If the compilation fails, find out if it's an error or just 315 315 more input is required - by extracting the message string from the exception … … 463 463 Unicode. This only causes the link failure if the extension uses any of the 464 464 ``PyUnicode_*()`` functions. It is also a problem if an extension uses any of 465 the Unicode-related format specifiers for :c func:`Py_BuildValue` (or similar) or466 parameter specifications for :c func:`PyArg_ParseTuple`.465 the Unicode-related format specifiers for :c:func:`Py_BuildValue` (or similar) or 466 parameter specifications for :c:func:`PyArg_ParseTuple`. 467 467 468 468 You can check the size of the Unicode character a Python interpreter is using by -
python/vendor/current/Doc/faq/general.rst
r2 r388 5 5 ================== 6 6 7 .. contents:: 7 .. only:: html 8 9 .. contents:: 10 8 11 9 12 General Information … … 158 161 The latest Python source distribution is always available from python.org, at 159 162 http://www.python.org/download/. The latest development sources can be obtained 160 via anonymous Subversion at http://svn.python.org/projects/python/trunk.163 via anonymous Mercurial access at http://hg.python.org/cpython. 161 164 162 165 The source distribution is a gzipped tar file containing the complete C source, … … 165 168 and run out of the box on most UNIX platforms. 166 169 167 .. XXX update link once the dev faq is relocated 168 169 Consult the `Developer FAQ <http://www.python.org/dev/faq/>`__ for more 170 Consult the `Developer FAQ <http://docs.python.org/devguide/faq>`__ for more 170 171 information on getting the source code and compiling it. 171 172 … … 222 223 news is available. 223 224 224 .. XXX update link once the dev faq is relocated225 226 225 You can also access the development version of Python through Subversion. See 227 http:// www.python.org/dev/faq/for details.226 http://docs.python.org/devguide/faq for details. 228 227 229 228 … … 240 239 `password reset procedure <http://bugs.python.org/user?@template=forgotten>`_. 241 240 242 .. XXX adapt link to dev guide243 244 241 For more information on how Python is developed, consult `the Python Developer's 245 Guide <http:// python.org/dev/>`_.242 Guide <http://docs.python.org/devguide/>`_. 246 243 247 244 -
python/vendor/current/Doc/faq/gui.rst
r2 r388 5 5 ========================== 6 6 7 .. contents::7 .. only:: html 8 8 9 General GUI Questions 10 ===================== 9 .. contents:: 11 10 12 11 What platform-independent GUI toolkits exist for Python? 13 -------------------------------------------------------- 12 ======================================================== 14 13 15 14 Depending on what platform(s) you are aiming at, there are several. … … 18 17 19 18 Tkinter 20 ''''''' 19 ------- 21 20 22 21 Standard builds of Python include an object-oriented interface to the Tcl/Tk … … 27 26 28 27 wxWidgets 29 ''''''''' 28 --------- 30 29 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>`__. 30 wxWidgets (http://www.wxwidgets.org) is a free, portable GUI class 31 library written in C++ that provides a native look and feel on a 32 number of platforms, with Windows, MacOS X, GTK, X11, all listed as 33 current stable targets. Language bindings are available for a number 34 of languages including Python, Perl, Ruby, etc. 34 35 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. 36 wxPython (http://www.wxpython.org) is the Python binding for 37 wxwidgets. While it often lags slightly behind the official wxWidgets 38 releases, it also offers a number of features via pure Python 39 extensions that are not available in other language bindings. There 40 is an active wxPython user and developer community. 39 41 40 wxWidgets supports Windows and MacOS; on Unix variants, 41 it supports both GTk+ and Motif toolkits. 42 Both wxWidgets and wxPython are free, open source, software with 43 permissive licences that allow their use in commercial products as 44 well as in freeware or shareware. 45 42 46 43 47 Qt 44 ''' 48 --- 45 49 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>`_. 50 There 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>`_). 53 PyQt 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>`_ 55 if you want to write proprietary applications. PySide is free for all applications. 56 57 Qt 4.5 upwards is licensed under the LGPL license; also, commercial licenses 58 are available from `Nokia <http://qt.nokia.com/>`_. 53 59 54 60 Gtk+ 55 '''' 61 ---- 56 62 57 63 PyGtk bindings for the `Gtk+ toolkit <http://www.gtk.org>`_ have been … … 59 65 60 66 FLTK 61 '''' 67 ---- 62 68 63 69 Python bindings for `the FLTK toolkit <http://www.fltk.org>`_, a simple yet … … 67 73 68 74 FOX 69 ''' 75 ---- 70 76 71 77 A wrapper for `the FOX toolkit <http://www.fox-toolkit.org/>`_ called `FXpy … … 75 81 76 82 OpenGL 77 '''''' 83 ------ 78 84 79 85 For OpenGL bindings, see `PyOpenGL <http://pyopengl.sourceforge.net>`_. … … 81 87 82 88 What platform-specific GUI toolkits exist for Python? 83 ----------------------------------------------------- 89 ======================================================== 84 90 85 91 `The Mac port <http://python.org/download/mac>`_ by Jack Jansen has a rich and … … 116 122 117 123 Build Tix with SAM enabled, perform the appropriate call to 118 :c func:`Tclsam_init`, etc. inside Python's124 :c:func:`Tclsam_init`, etc. inside Python's 119 125 :file:`Modules/tkappinit.c`, and link with libtclsam and libtksam (you 120 126 might include the Tix libraries as well). … … 125 131 126 132 Yes, 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 :c func:`XtAddInput()` call, which allows you133 code a bit. Tk has the equivalent of Xt's :c:func:`XtAddInput()` call, which allows you 128 134 to register a callback function which will be called from the Tk mainloop when 129 135 I/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 1 3 ################################### 2 4 Python Frequently Asked Questions 3 5 ################################### 4 5 :Release: |version|6 :Date: |today|7 6 8 7 .. toctree:: -
python/vendor/current/Doc/faq/library.rst
r2 r388 5 5 ========================= 6 6 7 .. contents:: 7 .. only:: html 8 9 .. contents:: 8 10 9 11 General Library Questions … … 15 17 Check :ref:`the Library Reference <library-index>` to see if there's a relevant 16 18 standard library module. (Eventually you'll learn what's in the standard 17 library and will able to skip this step.)19 library and will be able to skip this step.) 18 20 19 21 For third-party packages, search the `Python Package Index … … 29 31 dynamically loaded module implemented in C, C++ or other compiled language. 30 32 In this case you may not have the source file or it may be something like 31 mathmodule.c, somewhere in a C source directory (not on the Python Path).33 :file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path). 32 34 33 35 There are (at least) three kinds of modules in Python: … … 61 63 62 64 If you would like the script to be independent of where the Python interpreter 63 lives, you can use the "env" program. Almost all Unix variants support the64 following, assuming the Python interpreter is in a directory on the user's65 $PATH::65 lives, you can use the :program:`env` program. Almost all Unix variants support 66 the following, assuming the Python interpreter is in a directory on the user's 67 :envvar:`PATH`:: 66 68 67 69 #!/usr/bin/env python 68 70 69 *Don't* do this for CGI scripts. The $PATH variable for CGI scripts is often70 very minimal, so you need to use the actual absolute pathname of the71 *Don't* do this for CGI scripts. The :envvar:`PATH` variable for CGI scripts is 72 often very minimal, so you need to use the actual absolute pathname of the 71 73 interpreter. 72 74 73 Occasionally, a user's environment is so full that the /usr/bin/env program74 fails; or there's no env program at all. In that case, you can try the75 Occasionally, a user's environment is so full that the :program:`/usr/bin/env` 76 program fails; or there's no env program at all. In that case, you can try the 75 77 following hack (due to Alex Rezinsky):: 76 78 … … 92 94 .. XXX curses *is* built by default, isn't it? 93 95 94 For Unix variants : The standard Python source distribution comes with a curses95 module in the ``Modules/`` subdirectory, though it's not compiled by default96 ( note that this is not available in the Windows distribution -- there is no97 curses module for Windows ).98 99 The cursesmodule supports basic curses features as well as many additional96 For Unix variants the standard Python source distribution comes with a curses 97 module in the :source:`Modules` subdirectory, though it's not compiled by default. 98 (Note that this is not available in the Windows distribution -- there is no 99 curses module for Windows.) 100 101 The :mod:`curses` module supports basic curses features as well as many additional 100 102 functions from ncurses and SYSV curses such as colour, alternative character set 101 103 support, pads, and mouse support. This means the module isn't compatible with … … 111 113 112 114 The :mod:`atexit` module provides a register function that is similar to C's 113 onexit.115 :c:func:`onexit`. 114 116 115 117 … … 141 143 Smalltalk testing frameworks. 142 144 143 For testing, it helps to write the program so that it may be easily tested by 144 using good modular design.Your program should have almost all functionality145 To make testing easier, you should use good modular design in your program. 146 Your program should have almost all functionality 145 147 encapsulated in either functions or class methods -- and this sometimes has the 146 148 surprising and delightful effect of making the program run faster (because local … … 158 160 Once your program is organized as a tractable collection of functions and class 159 161 behaviours you should write test functions that exercise the behaviours. A test 160 suite can be associated with each module which automates a sequence of tests.162 suite that automates a sequence of tests can be associated with each module. 161 163 This sounds like a lot of work, but since Python is so terse and flexible it's 162 164 surprisingly easy. You can make coding much more pleasant and fun by writing … … 187 189 ----------------------------------------- 188 190 189 For Unix variants : There are several solutions. It's straightforward to do this191 For Unix variants there are several solutions. It's straightforward to do this 190 192 using curses, but curses is a fairly large module to learn. Here's a solution 191 193 without curses:: … … 206 208 try: 207 209 c = sys.stdin.read(1) 208 print "Got character", `c`210 print "Got character", repr(c) 209 211 except IOError: pass 210 212 finally: … … 274 276 time.sleep(10) 275 277 276 Instead of trying to guess how long a :func:`time.sleep` delay will be enough,278 Instead of trying to guess a good delay value for :func:`time.sleep`, 277 279 it's better to use some kind of semaphore mechanism. One idea is to use the 278 280 :mod:`Queue` module to create a queue object, let each thread append a token to … … 285 287 286 288 Use the :mod:`Queue` module to create a queue containing a list of jobs. The 287 :class:`~Queue.Queue` class maintains a list of objects with ``.put(obj)`` to288 add an item to the queue and ``.get()`` to return an item. The class will take 289 care of the locking necessary to ensure that each job is handed out exactly 290 once.289 :class:`~Queue.Queue` class maintains a list of objects and has a ``.put(obj)`` 290 method that adds items to the queue and a ``.get()`` method to return them. 291 The class will take care of the locking necessary to ensure that each job is 292 handed out exactly once. 291 293 292 294 Here's a trivial example:: … … 297 299 # assumes there will be no more work and exits. 298 300 # (Realistically workers will run until terminated.) 299 def worker 301 def worker(): 300 302 print 'Running worker' 301 303 time.sleep(0.1) … … 330 332 When run, this will produce the following output: 331 333 334 .. code-block:: none 335 332 336 Running worker 333 337 Running worker … … 344 348 ... 345 349 346 Consult the module's documentation for more details; the ``Queue`` class347 provides a featureful interface.350 Consult the module's documentation for more details; the :class:`~Queue.Queue` 351 class provides a featureful interface. 348 352 349 353 … … 351 355 ---------------------------------------------------- 352 356 353 A global interpreter lock (GIL) is used internally to ensure that only one354 thread runs in the Python VM at a time. In general, Python offers to switch357 A :term:`global interpreter lock` (GIL) is used internally to ensure that only 358 one thread runs in the Python VM at a time. In general, Python offers to switch 355 359 among threads only between bytecode instructions; how frequently it switches can 356 360 be set via :func:`sys.setcheckinterval`. Each bytecode instruction and … … 397 401 .. XXX link to dbeazley's talk about GIL? 398 402 399 The Global Interpreter Lock(GIL) is often seen as a hindrance to Python's403 The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's 400 404 deployment on high-end multiprocessor server machines, because a multi-threaded 401 405 Python program effectively only uses one CPU, due to the insistence that … … 411 415 Since then, the idea of getting rid of the GIL has occasionally come up but 412 416 nobody has found a way to deal with the expected slowdown, and users who don't 413 use threads would not be happy if their code ran at half atthe speed. Greg's417 use threads would not be happy if their code ran at half the speed. Greg's 414 418 free threading patch set has not been kept up-to-date for later Python versions. 415 419 … … 459 463 To truncate a file, open it using ``f = open(filename, "r+")``, and use 460 464 ``f.truncate(offset)``; offset defaults to the current seek position. There's 461 also `` `os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where462 ``fd``is the file descriptor (a small integer).465 also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where 466 *fd* is the file descriptor (a small integer). 463 467 464 468 The :mod:`shutil` module also contains a number of functions to work on files … … 494 498 string. 495 499 496 For data that is more regular (e.g. a homogeneous list of ints or thefloats),500 For data that is more regular (e.g. a homogeneous list of ints or floats), 497 501 you can also use the :mod:`array` module. 498 502 … … 504 508 integer representing the opened file. :func:`os.popen` creates a high-level 505 509 file object, the same type returned by the built-in :func:`open` function. 506 Thus, to read n bytes from a pipe pcreated with :func:`os.popen`, you need to510 Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to 507 511 use ``p.read(n)``. 508 512 … … 523 527 Warning: in general it is unwise to do this because you can easily cause a 524 528 deadlock where your process is blocked waiting for output from the child while 525 the child is blocked waiting for input from you. This can be caused b ecausethe526 parent expect s the child to output more text than it does, or it can be caused527 by data beingstuck in stdio buffers due to lack of flushing. The Python parent529 the child is blocked waiting for input from you. This can be caused by the 530 parent expecting the child to output more text than it does or by data being 531 stuck in stdio buffers due to lack of flushing. The Python parent 528 532 can of course explicitly flush the data it sends to the child before it reads 529 533 any output, but if the child is a naive C program it may have been written to … … 545 549 the result back. Unless the amount of data is very large, the easiest way to do 546 550 this is to write it to a temporary file and run the command with that temporary 547 file as input. The standard module :mod:`tempfile` exports a ``mktemp()``548 function to generate unique temporary file names. ::551 file as input. The standard module :mod:`tempfile` exports a 552 :func:`~tempfile.mktemp` function to generate unique temporary file names. :: 549 553 550 554 import tempfile … … 673 677 sys.stdout.write(httpobj.getfile().read()) 674 678 675 Note that in general for URL-encoded POST operations, query strings must be 676 quoted by using :func:`urllib.quote`. For example to send name="Guy Steele, 677 Jr.":: 678 679 >>> from urllib import quote 680 >>> x = quote("Guy Steele, Jr.") 681 >>> x 682 'Guy%20Steele,%20Jr.' 683 >>> query_string = "name="+x 684 >>> query_string 685 'name=Guy%20Steele,%20Jr.' 679 Note that in general for percent-encoded POST operations, query strings must be 680 quoted using :func:`urllib.urlencode`. For example, to send 681 ``name=Guy Steele, Jr.``:: 682 683 >>> import urllib 684 >>> urllib.urlencode({'name': 'Guy Steele, Jr.'}) 685 'name=Guy+Steele%2C+Jr.' 686 686 687 687 … … 691 691 .. XXX add modern template languages 692 692 693 There are many different modules available: 694 695 * HTMLgen is a class library of objects corresponding to all the HTML 3.2 markup 696 tags. It's used when you are writing in Python and wish to synthesize HTML 697 pages for generating a web or for CGI forms, etc. 698 699 * DocumentTemplate and Zope Page Templates are two different systems that are 700 part of Zope. 701 702 * Quixote's PTL uses Python syntax to assemble strings of text. 703 704 Consult the `Web Programming wiki pages 705 <http://wiki.python.org/moin/WebProgramming>`_ for more links. 693 You can find a collection of useful links on the `Web Programming wiki page 694 <http://wiki.python.org/moin/WebProgramming>`_. 706 695 707 696 … … 732 721 733 722 A Unix-only alternative uses sendmail. The location of the sendmail program 734 varies between systems; sometimes it is ``/usr/lib/sendmail``, sometime 723 varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes 735 724 ``/usr/sbin/sendmail``. The sendmail manual page will help you out. Here's 736 725 some sample code:: … … 799 788 Python types to files and strings, and back again. Although marshal does not do 800 789 fancy things like store instances or handle shared references properly, it does 801 run extremely fast. For example loading a half megabyte of data may take less790 run extremely fast. For example, loading a half megabyte of data may take less 802 791 than a third of a second. This often beats doing something more complex and 803 792 general such as using gdbm with pickle/shelve. … … 809 798 .. XXX update this, default protocol is 2/3 810 799 811 The default format used by the pickle module is a slow one that results in 812 readable pickles. Making it the default, but it would break backward 813 compatibility::800 By default :mod:`pickle` uses a relatively old and slow format for backward 801 compatibility. You can however specify other protocol versions that are 802 faster:: 814 803 815 804 largeString = 'z' * (100 * 1024) -
python/vendor/current/Doc/faq/programming.rst
r2 r388 5 5 =============== 6 6 7 .. contents:: 7 .. only:: html 8 9 .. contents:: 8 10 9 11 General Questions … … 172 174 173 175 L2 = [] 174 for i in range [3]:176 for i in range(3): 175 177 L2.append(L1[i]) 176 178 177 179 it is much shorter and far faster to use :: 178 180 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. 180 182 181 183 Note that the functionally-oriented built-in functions such as :func:`map`, … … 184 186 together:: 185 187 186 >>> zip([1, 2,3], [4,5,6])188 >>> zip([1, 2, 3], [4, 5, 6]) 187 189 [(1, 4), (2, 5), (3, 6)] 188 190 189 191 or to compute a number of sines:: 190 192 191 >>> map( math.sin, (1,2,3,4))192 [0.841470984808, 0.909297426826, 0.14112000806, 193 >>> map(math.sin, (1, 2, 3, 4)) 194 [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308] 193 195 194 196 The operation completes very quickly in such cases. 195 197 196 Other examples include the ``join()`` and ``split()`` methods of string objects. 198 Other examples include the ``join()`` and ``split()`` :ref:`methods 199 of string objects <string-methods>`. 197 200 For example if s1..s7 are large (10K+) strings then 198 201 ``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious 199 202 ``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many 200 203 subexpressions, whereas ``join()`` does all the copying in one pass. For 201 manipulating strings, use the ``replace()`` method on string objects. Use202 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``.204 manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods 205 on string objects <string-methods>`. Use regular expressions only when you're 206 not dealing with constant string patterns. You may still use :ref:`the old % 207 operations <string-formatting>` ``string % tuple`` and ``string % dictionary``. 205 208 206 209 Be sure to use the :meth:`list.sort` built-in method to do sorting, and see the … … 212 215 suppose you have a program that runs slowly and you use the profiler to 213 216 determine that a Python function ``ff()`` is being called lots of times. If you 214 notice that ``ff 217 notice that ``ff()``:: 215 218 216 219 def ff(x): … … 333 336 11 334 337 335 In Python3, you can do a similar thing in a nested scope using the336 :keyword:`nonlocal` keyword:337 338 .. doctest::339 :options: +SKIP340 341 >>> def foo():342 ... x = 10343 ... def bar():344 ... nonlocal x345 ... print x346 ... x += 1347 ... bar()348 ... print x349 >>> foo()350 10351 11352 353 338 354 339 What are the rules for local and global variables in Python? … … 370 355 371 356 357 Why do lambdas defined in a loop with different values all return the same result? 358 ---------------------------------------------------------------------------------- 359 360 Assume you use a for loop to define a few different lambdas (or even plain 361 functions), e.g.:: 362 363 >>> squares = [] 364 >>> for x in range(5): 365 ... squares.append(lambda: x**2) 366 367 This gives you a list that contains 5 lambdas that calculate ``x**2``. You 368 might expect that, when called, they would return, respectively, ``0``, ``1``, 369 ``4``, ``9``, and ``16``. However, when you actually try you will see that 370 they all return ``16``:: 371 372 >>> squares[2]() 373 16 374 >>> squares[4]() 375 16 376 377 This happens because ``x`` is not local to the lambdas, but is defined in 378 the outer scope, and it is accessed when the lambda is called --- not when it 379 is defined. At the end of the loop, the value of ``x`` is ``4``, so all the 380 functions now return ``4**2``, i.e. ``16``. You can also verify this by 381 changing the value of ``x`` and see how the results of the lambdas change:: 382 383 >>> x = 8 384 >>> squares[2]() 385 64 386 387 In order to avoid this, you need to save the values in variables local to the 388 lambdas, 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 394 Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed 395 when the lambda is defined so that it has the same value that ``x`` had at 396 that point in the loop. This means that the value of ``n`` will be ``0`` 397 in the first lambda, ``1`` in the second, ``2`` in the third, and so on. 398 Therefore each lambda will now return the correct result:: 399 400 >>> squares[2]() 401 4 402 >>> squares[4]() 403 16 404 405 Note that this behaviour is not peculiar to lambdas, but applies to regular 406 functions too. 407 408 372 409 How do I share global variables across modules? 373 410 ------------------------------------------------ … … 413 450 It's good practice if you import modules in the following order: 414 451 415 1. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re`` )452 1. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re`` 416 453 2. third-party library modules (anything installed in Python's site-packages 417 454 directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc. … … 422 459 write ``import m2``, even though it's legal. Write ``from package.sub import 423 460 m2`` instead. Relative imports can lead to a module being initialized twice, 424 leading to confusing bugs. 461 leading to confusing bugs. See :pep:`328` for details. 425 462 426 463 It is sometimes necessary to move imports to a function or class to avoid … … 487 524 488 525 526 .. index:: 527 single: argument; difference from parameter 528 single: parameter; difference from argument 529 530 .. _faq-argument-vs-parameter: 531 532 What is the difference between arguments and parameters? 533 -------------------------------------------------------- 534 535 :term:`Parameters <parameter>` are defined by the names that appear in a 536 function definition, whereas :term:`arguments <argument>` are the values 537 actually passed to a function when calling it. Parameters define what types of 538 arguments 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 548 the values ``42``, ``314``, and ``somevar`` are arguments. 549 550 489 551 How do I write a function with output parameters (call by reference)? 490 552 --------------------------------------------------------------------- … … 650 712 b = a 651 713 print b 652 <__main__.A instance at 0 16D07CC>714 <__main__.A instance at 0x16D07CC> 653 715 print a 654 <__main__.A instance at 0 16D07CC>716 <__main__.A instance at 0x16D07CC> 655 717 656 718 Arguably the class has a name: even though it is bound to two names and invoked … … 682 744 683 745 >>> "a" in "b", "a" 684 (False, ' 1')746 (False, 'a') 685 747 686 748 Since the comma is not an operator, but a separator between expressions the 687 749 above is evaluated as if you had entered:: 688 750 689 >>>("a" in "b"), "a"751 ("a" in "b"), "a" 690 752 691 753 not:: 692 754 693 >>> "a" in ("5", "a")755 "a" in ("b", "a") 694 756 695 757 The same is true of the various assignment operators (``=``, ``+=`` etc). They … … 709 771 710 772 For 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 a715 flaw: if *b* is zero (or empty, or ``None`` -- anything that tests false) then716 *c* will be selected instead. In many cases you can prove by looking at the717 code that this can't happen (e.g. because *b* is a constant or has a type that718 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 never722 false, so the wrong path is never taken; then applying ``[0]`` to the whole723 thing gets the *b* or *c* that you really wanted. Ugly, but it gets you there724 in the rare cases where it is really inconvenient to rewrite your code using725 'if'.726 727 The best course is usually to write a simple ``if...else`` statement. Another728 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_true734 else:735 return apply(on_true)736 else:737 if not isfunction(on_false):738 return on_false739 else:740 return apply(on_false)741 742 In most cases you'll pass b and c directly: ``q(a, b, c)``. To avoid evaluating743 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 are747 several answers: many languages do just fine without one; it can easily lead to748 less readable code; no sufficiently "Pythonic" syntax has been discovered; a749 search of the standard library found remarkably few places where using an750 if-then-else expression would make the code more understandable.751 752 In 2002, :pep:`308` was written proposing several possible syntaxes and the753 community was asked to vote on the issue. The vote was inconclusive. Most754 people liked one of the syntaxes, but also hated other syntaxes; many votes755 implied that people preferred no ternary operator rather than having a syntax756 they hated.757 773 758 774 … … 768 784 769 785 # 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), 771 787 range(10)) 772 788 … … 794 810 ------------------------------------------------ 795 811 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 812 To specify an octal digit, precede the octal value with a zero, and then a lower 813 or uppercase "o". For example, to set the variable "a" to the octal value "10" 814 (8 in decimal), type:: 815 816 >>> a = 0o10 800 817 >>> a 801 818 8 … … 813 830 814 831 815 Why does -22 / 10 return -3?816 ---------------------------- 832 Why does -22 // 10 return -3? 833 ----------------------------- 817 834 818 835 It's primarily driven by the desire that ``i % j`` have the same sign as ``j``. 819 836 If you want that, and also want:: 820 837 821 i == (i / j) * j + (i % j)838 i == (i // j) * j + (i % j) 822 839 823 840 then 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 the825 same sign as ``i``.841 hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have 842 the same sign as ``i``. 826 843 827 844 There are few real use cases for ``i % j`` when ``j`` is negative. When ``j`` … … 830 847 ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to 831 848 bite. 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. 832 855 833 856 … … 862 885 To convert, e.g., the number 144 to the string '144', use the built-in type 863 886 constructor :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. 887 the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see 888 the :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 891 manual for details. 868 892 869 893 … … 874 898 ability, try converting the string to a list or use the array module:: 875 899 900 >>> import io 876 901 >>> s = "Hello, world" 877 902 >>> a = list(s) … … 887 912 array('c', 'Hello, world') 888 913 >>> a[0] = 'y' ; print a 889 array('c', 'yello world')914 array('c', 'yello, world') 890 915 >>> a.tostring() 891 916 'yello, world' … … 954 979 955 980 Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all 956 occur ences of any line terminator from the end of the string ``S`` without981 occurrences of any line terminator from the end of the string ``S`` without 957 982 removing other trailing whitespace. If the string ``S`` represents more than 958 983 one line, with several empty lines at the end, the line terminators for all the … … 963 988 ... "\r\n") 964 989 >>> lines.rstrip("\n\r") 965 "line 1 "990 'line 1 ' 966 991 967 992 Since this is typically only desired when reading text one line at a time, using 968 993 ``S.rstrip()`` this way works well. 969 994 970 For older versions of Python, There are two partial substitutes:995 For older versions of Python, there are two partial substitutes: 971 996 972 997 - If you want to remove all trailing whitespace, use the ``rstrip()`` method of … … 989 1014 if the line uses something other than whitespace as a separator. 990 1015 991 For more complicated input parsing, regular expressions more powerful than C's992 :cfunc:`sscanf` and better suited for the task.1016 For more complicated input parsing, regular expressions are more powerful 1017 than C's :c:func:`sscanf` and better suited for the task. 993 1018 994 1019 … … 1094 1119 list, deleting duplicates as you go:: 1095 1120 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] 1102 1127 else: 1103 last = List[i]1128 last = mylist[i] 1104 1129 1105 1130 If all elements of the list may be used as dictionary keys (i.e. they are all … … 1107 1132 1108 1133 d = {} 1109 for x in List:1110 d[x] = x1111 List = d.values()1134 for x in mylist: 1135 d[x] = 1 1136 mylist = list(d.keys()) 1112 1137 1113 1138 In Python 2.5 and later, the following is possible instead:: 1114 1139 1115 List = list(set(List))1140 mylist = list(set(mylist)) 1116 1141 1117 1142 This converts the list into a set, thereby removing duplicates, and then back … … 1149 1174 You probably tried to make a multidimensional array like this:: 1150 1175 1151 A = [[None] * 2] * 31176 >>> A = [[None] * 2] * 3 1152 1177 1153 1178 This looks correct if you print it:: … … 1181 1206 1182 1207 Or, 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. 1184 1209 1185 1210 … … 1189 1214 Use a list comprehension:: 1190 1215 1191 result = [obj.method() for obj in List]1216 result = [obj.method() for obj in mylist] 1192 1217 1193 1218 More generically, you can try the following function:: … … 1200 1225 1201 1226 1227 Why does a_tuple[i] += ['item'] raise an exception when the addition works? 1228 --------------------------------------------------------------------------- 1229 1230 This is because of a combination of the fact that augmented assignment 1231 operators are *assignment* operators, and the difference between mutable and 1232 immutable objects in Python. 1233 1234 This discussion applies in general when augmented assignment operators are 1235 applied to elements of a tuple that point to mutable objects, but we'll use 1236 a ``list`` and ``+=`` as our exemplar. 1237 1238 If 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 1246 The reason for the exception should be immediately clear: ``1`` is added to the 1247 object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``, 1248 but 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 1250 a tuple points to. 1251 1252 Under the covers, what this augmented assignment statement is doing is 1253 approximately 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 1261 It is the assignment part of the operation that produces the error, since a 1262 tuple is immutable. 1263 1264 When 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 1272 The exception is a bit more surprising, and even more surprising is the fact 1273 that even though there was an error, the append worked:: 1274 1275 >>> a_tuple[0] 1276 ['foo', 'item'] 1277 1278 To 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 1280 is executed, and its return value is what gets used in the assignment statement; 1281 and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list 1282 and 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 1290 This is equivalent to:: 1291 1292 >>> result = a_list.__iadd__([1]) 1293 >>> a_list = result 1294 1295 The object pointed to by a_list has been mutated, and the pointer to the 1296 mutated object is assigned back to ``a_list``. The end result of the 1297 assignment is a no-op, since it is a pointer to the same object that ``a_list`` 1298 was previously pointing to, but the assignment still happens. 1299 1300 Thus, 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 1308 The ``__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, 1310 that final assignment still results in an error, because tuples are immutable. 1311 1312 1202 1313 Dictionaries 1203 1314 ============ … … 1214 1325 be presented in order sorted by the key. 1215 1326 1216 A more complicated solution is to subclass `` UserDict.UserDict`` to create a1327 A more complicated solution is to subclass ``dict`` to create a 1217 1328 ``SortedDict`` class that prints itself in a predictable order. Here's one 1218 1329 simpleminded implementation of such a class:: 1219 1330 1220 import UserDict, string 1221 1222 class SortedDict(UserDict.UserDict): 1331 class SortedDict(dict): 1223 1332 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__ 1233 1338 1234 1339 This will work for many common situations you might encounter, though it's far … … 1252 1357 strings by their uppercase values:: 1253 1358 1254 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform1359 tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform 1255 1360 tmp1.sort() 1256 1361 Usorted = [x[1] for x in tmp1] … … 1259 1364 each string:: 1260 1365 1261 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform1366 tmp2 = [(int(s[10:15]), s) for s in L] # Schwartzian transform 1262 1367 tmp2.sort() 1263 1368 Isorted = [x[1] for x in tmp2] … … 1296 1401 An alternative for the last step is:: 1297 1402 1298 result = []1299 for p in pairs: result.append(p[1])1403 >>> result = [] 1404 >>> for p in pairs: result.append(p[1]) 1300 1405 1301 1406 If you find this more legible, you might prefer to use this instead of the final … … 1365 1470 that does something:: 1366 1471 1367 def search 1472 def search(obj): 1368 1473 if isinstance(obj, Mailbox): 1369 1474 # ... code to search a mailbox … … 1468 1573 ----------------------------------------------------------- 1469 1574 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.1575 Both static data and static methods (in the sense of C++ or Java) are supported 1576 in Python. 1472 1577 1473 1578 For static data, simply define a class attribute. To assign a new value to the … … 1488 1593 1489 1594 Caution: 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. Rebinding1491 of a class-static data name must always specify the class whether inside a 1492 method ornot::1595 new and unrelated instance named "count" in ``self``'s own dict. Rebinding of a 1596 class-static data name must always specify the class whether inside a method or 1597 not:: 1493 1598 1494 1599 C.count = 314 … … 1620 1725 1621 1726 1727 Why does the result of ``id()`` appear to be not unique? 1728 -------------------------------------------------------- 1729 1730 The :func:`id` builtin returns an integer that is guaranteed to be unique during 1731 the lifetime of the object. Since in CPython, this is the object's memory 1732 address, it happens frequently that after an object is deleted from memory, the 1733 next freshly created object is allocated at the same position in memory. This 1734 is illustrated by this example: 1735 1736 >>> id(1000) 1737 13901272 1738 >>> id(2000) 1739 13901272 1740 1741 The two ids belong to different integer objects that are created before, and 1742 deleted immediately after execution of the ``id()`` call. To be sure that 1743 objects whose id you want to examine are still alive, create another reference 1744 to the object: 1745 1746 >>> a = 1000; b = 2000 1747 >>> id(a) 1748 13901272 1749 >>> id(b) 1750 13891296 1751 1752 1622 1753 Modules 1623 1754 ======= … … 1637 1768 directory. 1638 1769 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 .pycfile for a module1770 Running 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 1774 will be created since ``foo.py`` isn't being imported. 1775 1776 If you need to create ``foo.pyc`` -- that is, to create a ``.pyc`` file for a module 1646 1777 that is not imported -- you can, using the :mod:`py_compile` and 1647 1778 :mod:`compileall` modules. … … 1651 1782 1652 1783 >>> 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 can1784 >>> py_compile.compile('foo.py') # doctest: +SKIP 1785 1786 This will write the ``.pyc`` to the same location as ``foo.py`` (or you can 1656 1787 override that with the optional parameter ``cfile``). 1657 1788 -
python/vendor/current/Doc/faq/windows.rst
r2 r388 7 7 ===================== 8 8 9 .. contents:: 9 .. only:: html 10 11 .. contents:: 10 12 11 13 How do I run a Python program under Windows? … … 14 16 This is not necessarily a straightforward question. If you are already familiar 15 17 with 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. 18 obvious; otherwise, you might need a little more guidance. 19 19 20 20 .. sidebar:: |Python Development on XP|_ … … 33 33 *typing* Windows commands into what is variously referred to as a "DOS window" 34 34 or "Command prompt window". Usually you can create such a window from your 35 Start menu; under Windows 2000the menu selection is :menuselection:`Start -->35 Start menu; under Windows 7 the menu selection is :menuselection:`Start --> 36 36 Programs --> Accessories --> Command Prompt`. You should be able to recognize 37 37 when you have started such a window because you will see a Windows "command … … 43 43 might just as easily see something like:: 44 44 45 D:\ Steve\Projects\Python>45 D:\YourName\Projects\Python> 46 46 47 47 depending on how your computer has been set up and what else you have recently … … 50 50 51 51 You need to realize that your Python scripts have to be processed by another 52 program called the Python interpreter. The interpreter reads your script,52 program called the Python *interpreter*. The interpreter reads your script, 53 53 compiles it into bytecodes, and then executes the bytecodes to run your 54 54 program. So, how do you arrange for the interpreter to handle your Python? … … 57 57 "python" as an instruction to start the interpreter. If you have opened a 58 58 command 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 59 return.:: 60 61 C:\Users\YourName> python 62 63 You 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 62 66 Type "help", "copyright", "credits" or "license" for more information. 63 67 >>> … … 79 83 80 84 You 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 you85 --> Programs --> Python 2.7 --> Python (command line)` that results in you 82 86 seeing the ``>>>`` prompt in a new window. If so, the window will disappear 83 87 after you enter the Ctrl-Z character; Windows is running a single "python" … … 87 91 gives you a message like:: 88 92 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. 91 94 92 95 .. sidebar:: |Adding Python to DOS Path|_ … … 117 120 118 121 will probably tell you where it is installed; the usual location is something 119 like ``C:\Python2 3``. Otherwise you will be reduced to a search of your whole122 like ``C:\Python27``. Otherwise you will be reduced to a search of your whole 120 123 disk ... use :menuselection:`Tools --> Find` or hit the :guilabel:`Search` 121 124 button and look for "python.exe". Supposing you discover that Python is 122 installed in the ``C:\Python2 3`` directory (the default at the time of writing),125 installed in the ``C:\Python27`` directory (the default at the time of writing), 123 126 you should make sure that entering the command :: 124 127 125 c:\Python2 3\python128 c:\Python27\python 126 129 127 130 starts 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 131 an "Enter" to get out of it). Once you have verified the directory, you can 132 add it to the system path to make it easier to start Python by just running 133 the ``python`` command. This is currently an option in the installer as of 134 CPython 2.7. 135 136 More information about environment variables can be found on the 137 :ref:`Using Python on Windows <setting-envvars>` page. 206 138 207 139 How do I make Python scripts executable? 208 140 ---------------------------------------- 209 141 210 On Windows 2000, the standard Python installer already associates the .py142 On Windows, the standard Python installer already associates the .py 211 143 extension with a file type (Python.File) and gives that file type an open 212 144 command that runs the interpreter (``D:\Program Files\Python\python.exe "%1" … … 214 146 'foo.py'. If you'd rather be able to execute the script by simple typing 'foo' 215 147 with 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 to218 run a script with 'foo.py', but a longtime bug in the NT command processor219 prevents you from redirecting the input or output of any script executed in this220 way. This is often important.221 222 The incantation for making a Python script executable under WinNT is to give the223 file an extension of .cmd and add the following as the first line::224 225 @setlocal enableextensions & python -x %~f0 %* & goto :EOF226 227 148 228 149 Why does Python sometimes take so long to start? … … 243 164 244 165 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 166 How do I make an executable from a Python script? 167 ------------------------------------------------- 168 169 See http://www.py2exe.org/ for a distutils extension that allows you 170 to create console and GUI executables from Python code. 261 171 262 172 Is a ``*.pyd`` file the same as a DLL? … … 287 197 1. Do _not_ build Python into your .exe file directly. On Windows, Python must 288 198 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 303 211 ``LoadLibraryEx()`` routine. The code must also use access routines and data 304 212 in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained … … 308 216 Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe 309 217 first. 218 219 .. XXX what about static linking? 310 220 311 221 2. If you use SWIG, it is easy to create a Python "extension module" that will … … 373 283 (defined in your extension module) that contains read() and write() methods. 374 284 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 up380 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\ScriptMap385 386 and enter the following line (making any specific changes that your system may387 need)::388 389 .py :REG_SZ: c:\<path to python>\python.exe -u %s %s390 391 This line will allow you to call your script with a simple reference like:392 ``http://yourserver/scripts/yourscript.py`` provided "scripts" is an393 "executable" directory for your server (which it usually is by default). The394 :option:`-u` flag specifies unbuffered and binary mode for stdin - needed when395 working with binary data.396 397 In addition, it is recommended that using ".py" may not be a good idea for the398 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 CGI402 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 file408 ``httpd.conf``, add the following line at the end of the file::409 410 ScriptInterpreterSource Registry411 412 Then, give your Python CGI-scripts the extension .py and put them in the cgi-bin413 directory.414 415 416 285 How do I keep editors from inserting tabs into my Python source? 417 286 ---------------------------------------------------------------- … … 442 311 -------------------------------------- 443 312 444 Use win32api:: 313 Prior to Python 2.7 and 3.2, to terminate a process, you can use :mod:`ctypes`:: 314 315 import ctypes 445 316 446 317 def kill(pid): 447 318 """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 323 In 2.7 and 3.2, :func:`os.kill` is implemented similar to the above function, 324 with the additional feature of being able to send CTRL+C and CTRL+BREAK 325 to console subprocesses which are designed to handle those signals. See 326 :func:`os.kill` for further details. 561 327 562 328 How do I extract the downloaded documentation on Windows? … … 571 337 http://www.winzip.com.) 572 338 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 or578 cw3215.dll is missing.579 580 Cause: you have an old Tcl/Tk DLL built with cygwin in your path (probably581 ``C:\Windows``). You must use the Tcl/Tk DLLs from the standard Tcl/Tk582 installation (Python 1.5.2 comes with one).583 584 585 Warning about CTL3D32 version from installer586 --------------------------------------------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 message596 means what it says: you have the wrong version of this DLL for your operating597 system. The Python installation did not cause this -- something else you598 installed previous to this overwrote the DLL that came with your OS (probably599 older shareware of some sort, but there's no way to tell now). If you search600 for "CTL3D32" using any search engine (AltaVista, for example), you'll find601 hundreds and hundreds of web pages complaining about the same problem with602 all sorts of installation programs. They'll point you to ways to get the603 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 to607 http://www.burtonsys.com/downloads.html and click on "ctl3dfix.zip".
Note:
See TracChangeset
for help on using the changeset viewer.