Merged revisions 62425-62429,62434-62436,62441,62444,62446-62448,62450-62455,62463,62465-62466,62469,62474,62476-62478,62480,62485,62492,62497-62498,62500,62507,62513-62514,62516,62521,62531,62535,62545-62546,62548-62551,62553-62559,62569,62574,62577,62593,62595,62604-62606,62608,62616,62626-62627,62636,62638,62644-62645,62647-62648,62651-62653,62656,62661,62663,62680,62686-62687,62696,62699-62703,62711 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

................
  r62425 | andrew.kuchling | 2008-04-21 03:45:57 +0200 (Mon, 21 Apr 2008) | 1 line

  Comment typo
................
  r62426 | mark.dickinson | 2008-04-21 03:55:50 +0200 (Mon, 21 Apr 2008) | 2 lines

  Silence 'r may be used uninitialized' compiler warning.
................
  r62427 | andrew.kuchling | 2008-04-21 04:08:00 +0200 (Mon, 21 Apr 2008) | 1 line

  Markup fix
................
  r62428 | andrew.kuchling | 2008-04-21 04:08:13 +0200 (Mon, 21 Apr 2008) | 1 line

  Wording changes
................
  r62429 | andrew.kuchling | 2008-04-21 04:14:24 +0200 (Mon, 21 Apr 2008) | 1 line

  Add various items
................
  r62434 | thomas.heller | 2008-04-21 15:46:55 +0200 (Mon, 21 Apr 2008) | 1 line

  Fix typo.
................
  r62435 | david.goodger | 2008-04-21 16:40:22 +0200 (Mon, 21 Apr 2008) | 1 line

  corrections ("reStructuredText" is one word)
................
  r62436 | david.goodger | 2008-04-21 16:43:33 +0200 (Mon, 21 Apr 2008) | 1 line

  capitalization
................
  r62441 | gregory.p.smith | 2008-04-21 19:46:40 +0200 (Mon, 21 Apr 2008) | 2 lines

  explicitly flush after the ... since there wasn't a newline
................
  r62444 | jeroen.ruigrok | 2008-04-21 22:15:39 +0200 (Mon, 21 Apr 2008) | 2 lines

  Windows x64 also falls under VER_PLATFORM_WIN32_NT.
................
  r62446 | gregory.p.smith | 2008-04-21 23:31:08 +0200 (Mon, 21 Apr 2008) | 3 lines

  If sys.stdin is not a tty, fall back to default_getpass after printing
  a warning instead of failing with a termios.error.
................
  r62447 | mark.dickinson | 2008-04-22 00:32:24 +0200 (Tue, 22 Apr 2008) | 8 lines

  test_math and test_cmath are failing on the FreeBSD 6.2 trunk buildbot,
  apparently because tanh(-0.) loses the sign of zero on that platform.
  If true, this is a bug in FreeBSD.

  Added a configure test to verify this.  I still need to figure out
  how best to deal with this failure.
................
  r62448 | amaury.forgeotdarc | 2008-04-22 00:35:30 +0200 (Tue, 22 Apr 2008) | 7 lines

  Issue 2665: On Windows, sys.stderr does not contain a valid file when running without a console.
  It seems to work, but will fail at the first flush.

  This causes IDLE to crash when too many warnings are printed.

  Will backport.
................
  r62450 | benjamin.peterson | 2008-04-22 00:57:00 +0200 (Tue, 22 Apr 2008) | 2 lines

  Fix Sphinx warnings
................
  r62451 | mark.dickinson | 2008-04-22 02:54:27 +0200 (Tue, 22 Apr 2008) | 3 lines

  Make configure test for tanh(-0.) == -0. committed in r62447 actually
  work.  (The test wasn't properly linked with libm.  Sigh.)
................
  r62452 | benjamin.peterson | 2008-04-22 04:16:03 +0200 (Tue, 22 Apr 2008) | 2 lines

  Various io doc updates
................
  r62453 | neal.norwitz | 2008-04-22 07:07:47 +0200 (Tue, 22 Apr 2008) | 1 line

  Add Thomas Lee
................
  r62454 | gregory.p.smith | 2008-04-22 10:08:41 +0200 (Tue, 22 Apr 2008) | 8 lines

  Major improvements:
  * Default to using /dev/tty for the password prompt and input before
    falling back to sys.stdin and sys.stderr.
  * Use sys.stderr instead of sys.stdout.
  * print the 'password may be echoed' warning to stream used to display
    the prompt rather than always sys.stderr.
  * warn() with GetPassWarning when input may be echoed.
................
  r62455 | gregory.p.smith | 2008-04-22 10:11:33 +0200 (Tue, 22 Apr 2008) | 2 lines

  update the getpass entry
................
  r62463 | amaury.forgeotdarc | 2008-04-22 23:14:41 +0200 (Tue, 22 Apr 2008) | 5 lines

  Issue #2670: urllib2.build_opener() failed when two handlers
  derive the same default base class.

  Will backport.
................
  r62465 | skip.montanaro | 2008-04-23 00:45:09 +0200 (Wed, 23 Apr 2008) | 3 lines

  Factor in documentation changes from issue 1753732.
................
  r62466 | gregory.p.smith | 2008-04-23 03:06:42 +0200 (Wed, 23 Apr 2008) | 2 lines

  syntax fixup
................
  r62469 | benjamin.peterson | 2008-04-23 22:38:06 +0200 (Wed, 23 Apr 2008) | 2 lines

  #2673 Fix example typo in optparse docs
................
  r62474 | martin.v.loewis | 2008-04-24 11:50:50 +0200 (Thu, 24 Apr 2008) | 2 lines

  Add Guilherme Polo.
................
  r62476 | martin.v.loewis | 2008-04-24 15:16:36 +0200 (Thu, 24 Apr 2008) | 3 lines

  Remove Py_Refcnt, Py_Type, Py_Size, as they were added only
  for backwards compatibility, yet 2.5 did not have them at all.
................
  r62477 | martin.v.loewis | 2008-04-24 15:17:24 +0200 (Thu, 24 Apr 2008) | 2 lines

  Fix typo.
................
  r62478 | martin.v.loewis | 2008-04-24 15:18:03 +0200 (Thu, 24 Apr 2008) | 2 lines

  Add Jesus Cea.
................
  r62480 | amaury.forgeotdarc | 2008-04-24 20:07:05 +0200 (Thu, 24 Apr 2008) | 4 lines

  Issue2681: the literal 0o8 was wrongly accepted, and evaluated as float(0.0).
  This happened only when 8 is the first digit.
  Credits go to Lukas Meuser.
................
  r62485 | amaury.forgeotdarc | 2008-04-24 22:10:26 +0200 (Thu, 24 Apr 2008) | 5 lines

  Disable gc when running test_trace, or we may record the __del__ of collected objects.

  See http://mail.python.org/pipermail/python-checkins/2008-April/068633.html
  the extra events perfectly match several calls to socket._fileobject.__del__()
................
  r62492 | neal.norwitz | 2008-04-25 05:40:17 +0200 (Fri, 25 Apr 2008) | 1 line

  Fix typo (now -> no)
................
  r62497 | armin.rigo | 2008-04-25 11:35:18 +0200 (Fri, 25 Apr 2008) | 2 lines

  A new crasher.
................
  r62498 | thomas.heller | 2008-04-25 17:44:16 +0200 (Fri, 25 Apr 2008) | 1 line

  Add from_buffer and from_buffer_copy class methods to ctypes types.
................
  r62500 | mark.dickinson | 2008-04-25 18:59:09 +0200 (Fri, 25 Apr 2008) | 3 lines

  Issue 2635: fix bug in the fix_sentence_endings option to textwrap.fill.
................
  r62507 | benjamin.peterson | 2008-04-25 23:43:56 +0200 (Fri, 25 Apr 2008) | 2 lines

  Allow test_import to work when it is invoked directly
................
  r62513 | georg.brandl | 2008-04-26 20:31:07 +0200 (Sat, 26 Apr 2008) | 2 lines

  #2691: document PyLong (s)size_t APIs, patch by Alexander Belopolsky.
................
  r62514 | georg.brandl | 2008-04-26 20:32:17 +0200 (Sat, 26 Apr 2008) | 2 lines

  Add missing return type to dealloc.
................
  r62516 | alexandre.vassalotti | 2008-04-27 02:52:24 +0200 (Sun, 27 Apr 2008) | 2 lines

  Fixed URL of PEP 205 in weakref's module docstring.
................
  r62521 | georg.brandl | 2008-04-27 11:39:59 +0200 (Sun, 27 Apr 2008) | 2 lines

  #2677: add note that not all functions may accept keyword args.
................
  r62531 | georg.brandl | 2008-04-27 19:38:55 +0200 (Sun, 27 Apr 2008) | 2 lines

  Use correct XHTML tags.
................
  r62535 | benjamin.peterson | 2008-04-27 20:14:39 +0200 (Sun, 27 Apr 2008) | 2 lines

  #2700 Document PyNumber_ToBase
................
  r62545 | skip.montanaro | 2008-04-27 22:53:57 +0200 (Sun, 27 Apr 2008) | 1 line

  minor wording changes, rewrap a few lines
................
  r62546 | kurt.kaiser | 2008-04-27 23:07:41 +0200 (Sun, 27 Apr 2008) | 7 lines

  Home / Control-A toggles between left margin and end of leading white
  space.  Patch 1196903 Jeff Shute.

  M    idlelib/PyShell.py
  M    idlelib/EditorWindow.py
  M    idlelib/NEWS.txt
................
  r62548 | kurt.kaiser | 2008-04-27 23:38:05 +0200 (Sun, 27 Apr 2008) | 2 lines

  Improved AutoCompleteWindow logic.  Patch 2062 Tal Einat.
................
  r62549 | kurt.kaiser | 2008-04-27 23:52:19 +0200 (Sun, 27 Apr 2008) | 4 lines

  Autocompletion of filenames now support alternate separators, e.g. the
  '/' char on Windows.  Patch 2061 Tal Einat.
................
  r62550 | skip.montanaro | 2008-04-28 00:49:56 +0200 (Mon, 28 Apr 2008) | 6 lines

  A few small changes:
  * The only exception we should catch when trying to import cStringIO is an
    ImportError.
  * Delete the function signatures embedded in the mk*temp docstrings.
  * The tempdir global variable was initialized twice.
................
  r62551 | skip.montanaro | 2008-04-28 00:52:02 +0200 (Mon, 28 Apr 2008) | 4 lines

  Wrap some long paragraphs and include the default values for optional
  function parameters.
................
  r62553 | skip.montanaro | 2008-04-28 04:57:23 +0200 (Mon, 28 Apr 2008) | 7 lines

  Minor cleanups:
  * Avoid creating unused local variables where we can.  Where we can't prefix
    the unused variables with '_'.
  * Avoid shadowing builtins where it won't change the external interface of a
    function.
  * Use None as default path arg to readmodule and readmodule_ex.
................
  r62554 | skip.montanaro | 2008-04-28 04:59:45 +0200 (Mon, 28 Apr 2008) | 6 lines

  Correct documentation to match implementation: "Class" instead of
  "class_descriptor", "Function" instead of "function_descriptor".  Note
  default path value for readmodule*.  Wrap some long paragraphs.  Don't
  mention 'inpackage' which isn't part of the public API.
................
  r62555 | brett.cannon | 2008-04-28 05:23:50 +0200 (Mon, 28 Apr 2008) | 5 lines

  Fix a bug introduced by the warnings rewrite where tracebacks were being
  improperly indented.

  Closes issue #2699.
................
  r62556 | skip.montanaro | 2008-04-28 05:25:37 +0200 (Mon, 28 Apr 2008) | 2 lines

  Wrap some long lines.
................
  r62557 | skip.montanaro | 2008-04-28 05:27:53 +0200 (Mon, 28 Apr 2008) | 6 lines

  Get rid of _test(), _main(), _debug() and _check().  Tests are no longer
  needed (better set available in Lib/test/test_robotparser.py).  Clean up a
  few PEP 8 nits (compound statements on a single line, whitespace around
  operators).
................
  r62558 | brett.cannon | 2008-04-28 06:50:06 +0200 (Mon, 28 Apr 2008) | 3 lines

  Rename the test_traceback_print() function to traceback_print() to prevent
  test_capi from automatically calling the function.
................
  r62559 | georg.brandl | 2008-04-28 07:16:30 +0200 (Mon, 28 Apr 2008) | 2 lines

  Fix markup.
................
  r62569 | amaury.forgeotdarc | 2008-04-28 23:07:06 +0200 (Mon, 28 Apr 2008) | 5 lines

  test_sundry performs minimal tests (a simple import...) on modules that are not tested otherwise.

  Some of them now have tests and can be removed.
  Only 70 to go...
................
  r62574 | andrew.kuchling | 2008-04-29 04:03:54 +0200 (Tue, 29 Apr 2008) | 1 line

  Strip down SSL docs; I'm not managing to get test programs working, so I'll just give a minimal description
................
  r62577 | martin.v.loewis | 2008-04-29 08:10:53 +0200 (Tue, 29 Apr 2008) | 2 lines

  Add Rodrigo and Heiko.
................
  r62593 | nick.coghlan | 2008-04-30 16:23:36 +0200 (Wed, 30 Apr 2008) | 1 line

  Update command line usage documentation to reflect 2.6 changes (also includes some minor cleanups). Addresses TODO list issue 2258
................
  r62595 | andrew.kuchling | 2008-04-30 18:19:55 +0200 (Wed, 30 Apr 2008) | 1 line

  Typo fix
................
  r62604 | benjamin.peterson | 2008-04-30 23:03:58 +0200 (Wed, 30 Apr 2008) | 2 lines

  make test_support's captured_output a bit more robust when exceptions happen
................
  r62605 | georg.brandl | 2008-04-30 23:08:42 +0200 (Wed, 30 Apr 2008) | 2 lines

  #1748: use functools.wraps instead of rolling own metadata update.
................
  r62606 | benjamin.peterson | 2008-04-30 23:25:55 +0200 (Wed, 30 Apr 2008) | 2 lines

  Remove some from __future__ import with_statements
................
  r62608 | benjamin.peterson | 2008-05-01 00:03:36 +0200 (Thu, 01 May 2008) | 2 lines

  Fix typo in whatsnew
................
  r62616 | georg.brandl | 2008-05-01 20:24:32 +0200 (Thu, 01 May 2008) | 2 lines

  Fix synopsis.
................
  r62626 | brett.cannon | 2008-05-02 04:25:09 +0200 (Fri, 02 May 2008) | 6 lines

  Fix a backwards-compatibility mistake where a new optional argument for
  warnings.showwarning() was being used. This broke pre-existing replacements for
  the function since they didn't support the extra argument.

  Closes issue 2705.
................
  r62627 | gregory.p.smith | 2008-05-02 09:26:52 +0200 (Fri, 02 May 2008) | 20 lines

  This should fix issue2632.  A long description of the two competing
  problems is in the bug report (one old, one recently introduced trying
  to fix the old one).  In short:

  buffer data during socket._fileobject.read() and readlines() within a
  cStringIO object instead of a [] of str()s returned from the recv()
  call.

  This prevents excessive memory use due to the size parameter being
  passed to recv() being grossly larger than the actual size of the data
  returned *and* prevents excessive cpu usage due to looping in python
  calling recv() with a very tiny size value if min() is used as the
  previous memory-use bug "fix" did.

  It also documents what the socket._fileobject._rbufsize member is
  actually used for.

  This is a candidate for back porting to 2.5.
................
  r62636 | mark.hammond | 2008-05-02 14:48:15 +0200 (Fri, 02 May 2008) | 2 lines

  #2581: Vista UAC/elevation support for bdist_wininst
................
  r62638 | facundo.batista | 2008-05-02 19:39:00 +0200 (Fri, 02 May 2008) | 3 lines


  Fixed some test structures. Thanks Mark Dickinson.
................
  r62644 | ronald.oussoren | 2008-05-02 21:45:11 +0200 (Fri, 02 May 2008) | 7 lines

  Fix for issue #2573: Can't change the framework name on OS X builds

  This introduces a new configure option: --with-framework-name=NAME
  (defaulting to 'Python'). This allows you to install several copies
  of the Python framework with different names (such as a normal build
  and a debug build).
................
  r62645 | ronald.oussoren | 2008-05-02 21:58:56 +0200 (Fri, 02 May 2008) | 2 lines

  Finish fix for issue2573, previous patch was incomplete.
................
  r62647 | martin.v.loewis | 2008-05-02 23:30:20 +0200 (Fri, 02 May 2008) | 13 lines

  Merged revisions 62263-62646 via svnmerge from
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3

  ........
    r62470 | david.wolever | 2008-04-24 02:11:07 +0200 (Do, 24 Apr 2008) | 3 lines

    Fixed up and applied the patch for #2431 -- speeding up 2to3 with a lookup table.
  ........
    r62646 | martin.v.loewis | 2008-05-02 23:29:27 +0200 (Fr, 02 Mai 2008) | 2 lines

    Fix whitespace.
  ........
................
  r62648 | ronald.oussoren | 2008-05-02 23:42:35 +0200 (Fri, 02 May 2008) | 4 lines

  Fix for #1905: PythonLauncher not working correctly on OSX 10.5/Leopard

  This fixes both Python Launchar and the terminalcommand module.
................
  r62651 | ronald.oussoren | 2008-05-02 23:54:56 +0200 (Fri, 02 May 2008) | 2 lines

  Fix for issue #2520 (cannot import macerrors)
................
  r62652 | benjamin.peterson | 2008-05-03 00:12:58 +0200 (Sat, 03 May 2008) | 2 lines

  capitalization nit for reStructuredText
................
  r62653 | brett.cannon | 2008-05-03 03:02:41 +0200 (Sat, 03 May 2008) | 2 lines

  Fix some indentation errors.
................
  r62656 | brett.cannon | 2008-05-03 05:19:39 +0200 (Sat, 03 May 2008) | 6 lines

  Fix the C implementation of 'warnings' to infer the filename of the module that
  raised an exception properly when __file__ is not set, __name__ == '__main__',
  and sys.argv[0] is a false value.

  Closes issue2743.
................
  r62661 | amaury.forgeotdarc | 2008-05-03 14:21:13 +0200 (Sat, 03 May 2008) | 8 lines

  In test_io, StatefulIncrementalDecoderTest was not part of the test suite.
  And of course, the test failed:
  a bytearray was used without reason in io.TextIOWrapper.tell().

  The difference is that iterating over bytes (i.e. str in python2.6) returns 1-char bytes,
  whereas bytearrays yield integers.
  This code should still work with python3.0
................
  r62663 | benjamin.peterson | 2008-05-03 17:56:42 +0200 (Sat, 03 May 2008) | 2 lines

  The compiling struct is now passed around to all AST helpers (see issue 2720)
................
  r62680 | benjamin.peterson | 2008-05-03 23:35:18 +0200 (Sat, 03 May 2008) | 2 lines

  Moved testing of builtin types out of test_builtin and into type specific modules
................
  r62686 | mark.dickinson | 2008-05-04 04:25:46 +0200 (Sun, 04 May 2008) | 4 lines

  Make sure that Context traps and flags dictionaries have values 0 and 1
  (as documented) rather than True and False.
................
  r62687 | benjamin.peterson | 2008-05-04 05:05:49 +0200 (Sun, 04 May 2008) | 2 lines

  Fix typo in whatsnew
................
  r62696 | georg.brandl | 2008-05-04 11:15:04 +0200 (Sun, 04 May 2008) | 2 lines

  #2752: wrong meaning of '' for socket host.
................
  r62699 | christian.heimes | 2008-05-04 13:50:53 +0200 (Sun, 04 May 2008) | 1 line

  Added note that Python requires at least Win2k SP4
................
  r62700 | gerhard.haering | 2008-05-04 14:59:57 +0200 (Sun, 04 May 2008) | 3 lines

  SQLite requires 64-bit integers in order to build. So the whole HAVE_LONG_LONG
  #ifdefing was useless.
................
  r62701 | gerhard.haering | 2008-05-04 15:15:12 +0200 (Sun, 04 May 2008) | 3 lines

  Applied sqliterow-richcmp.diff patch from Thomas Heller in Issue2152. The
  sqlite3.Row type is now correctly hashable.
................
  r62702 | gerhard.haering | 2008-05-04 15:42:44 +0200 (Sun, 04 May 2008) | 5 lines

  Implemented feature request 2157: Converter names are cut off at '('
  characters. This avoids the common case of something like 'NUMBER(10)' not
  being parsed as 'NUMBER', like expected. Also corrected the docs about
  converter names being case-sensitive. They aren't any longer.
................
  r62703 | georg.brandl | 2008-05-04 17:45:05 +0200 (Sun, 04 May 2008) | 2 lines

  #2757: Remove spare newline.
................
  r62711 | benjamin.peterson | 2008-05-04 21:10:02 +0200 (Sun, 04 May 2008) | 2 lines

  Fix typo in bugs.rst
................
This commit is contained in:
Christian Heimes 2008-05-04 22:42:01 +00:00
parent c0b6cc8af1
commit 81ee3efede
108 changed files with 2328 additions and 1484 deletions

View File

@ -18,8 +18,8 @@ Many thanks go to:
* Fred L. Drake, Jr., the creator of the original Python documentation toolset
and writer of much of the content;
* the `docutils <http://docutils.sf.net/>`_ project for creating
reStructuredText and the docutils suite;
* the `Docutils <http://docutils.sf.net/>`_ project for creating
reStructuredText and the Docutils suite;
* Fredrik Lundh for his `Alternative Python Reference
<http://effbot.org/zone/pyref.htm>`_ project from which Sphinx got many good
ideas.

View File

@ -37,7 +37,7 @@ The submission form has a number of fields. For the "Title" field, enter a
"Type" field, select the type of your problem; also select the "Component" and
"Versions" to which the bug relates.
In the "Change Note" field, describe the problem in detail, including what you
In the "Comment" field, describe the problem in detail, including what you
expected to happen and what did happen. Be sure to include whether any
extension modules were involved, and what hardware and software platform you
were using (including version information as appropriate).

View File

@ -52,14 +52,14 @@ All integers are implemented as "long" integer objects of arbitrary size.
.. cfunction:: PyObject* PyLong_FromSsize_t(Py_ssize_t v)
Return a new :ctype:`PyLongObject` object with a value of *v*, or *NULL*
on failure.
Return a new :ctype:`PyLongObject` object from a C :ctype:`Py_ssize_t`, or
*NULL* on failure.
.. cfunction:: PyObject* PyLong_FromSize_t(size_t v)
Return a new :ctype:`PyLongObject` object with a value of *v*, or *NULL*
on failure.
Return a new :ctype:`PyLongObject` object from a C :ctype:`size_t`, or
*NULL* on failure.
.. cfunction:: PyObject* PyLong_FromLongLong(PY_LONG_LONG v)
@ -127,6 +127,17 @@ All integers are implemented as "long" integer objects of arbitrary size.
If an exception is set because of type errors, also return -1.
.. cfunction:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
.. index::
single: PY_SSIZE_T_MAX
single: OverflowError (built-in exception)
Return a C :ctype:`Py_ssize_t` representation of the contents of *pylong*. If
*pylong* is greater than :const:`PY_SSIZE_T_MAX`, an :exc:`OverflowError` is raised
and ``-1`` will be returned.
.. cfunction:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
.. index::

View File

@ -259,6 +259,17 @@ Number Protocol
TypeError exception raised on failure.
.. cfunction:: PyObject* PyNumber_ToBase(PyObject *n, int base)
Returns the the integer *n* converted to *base* as a string with a base
marker of ``'0b'``, ``'0o'``, or ``'0x'`` if appended applicable. When
*base* is not 2, 8, 10, or 16, the format is ``'x#num'`` where x is the
base. If *n* is not an int object, it is converted with
:cfunc:`PyNumber_Index` first.
.. versionadded:: 2.6
.. cfunction:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)
Returns *o* converted to a Py_ssize_t value if *o* can be interpreted as an

View File

@ -426,6 +426,13 @@ built-in functions in the installation script.
also the configuration. For details refer to Microsoft's documentation of the
:cfunc:`SHGetSpecialFolderPath` function.
Vista User Access Control (UAC)
===============================
Starting with Python 2.6, bdist_wininst supports a :option:`--user-access-control`
option. The default is 'none' (meaning no UAC handling is done), and other
valid values are 'auto' (meaning prompt for UAC elevation if Python was
installed for all users) and 'force' (meaning always prompt for elevation)
.. function:: create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]])
@ -437,5 +444,3 @@ built-in functions in the installation script.
and *iconindex* is the index of the icon in the file *iconpath*. Again, for
details consult the Microsoft documentation for the :class:`IShellLink`
interface.

View File

@ -70,7 +70,7 @@ The ``CFBase``, ``CFArray``, ``CFData``, ``CFDictionary``, ``CFString`` and
.. module:: Carbon.CG
:platform: Mac
:synopsis: Interface to the Component Manager.
:synopsis: Interface to Core Graphics.

View File

@ -1948,6 +1948,28 @@ Data types
exact, they are methods of the :term:`metaclass`):
.. method:: _CData.from_buffer(source[, offset])
This method returns a ctypes instance that shares the buffer of
the ``source`` object. The ``source`` object must support the
writeable buffer interface. The optional ``offset`` parameter
specifies an offset into the source buffer in bytes; the default
is zero. If the source buffer is not large enough a ValueError
is raised.
.. versionadded:: 2.6
.. method:: _CData.from_buffer_copy(source[, offset])
This method creates a ctypes instance, the buffer is copied from
the source object buffer which must be readable. The optional
``offset`` parameter specifies an offset into the source buffer
in bytes; the default is zero. If the source buffer is not
large enough a ValueError is raised.
.. versionadded:: 2.6
.. method:: from_address(address)
This method returns a ctypes type instance using the memory specified by

View File

@ -14,11 +14,27 @@ The :mod:`getpass` module provides two functions:
Prompt the user for a password without echoing. The user is prompted using the
string *prompt*, which defaults to ``'Password: '``. On Unix, the prompt is
written to the file-like object *stream*, which defaults to ``sys.stdout`` (this
argument is ignored on Windows).
written to the file-like object *stream*. *stream* defaults to the
controlling terminal (/dev/tty) or if that is unavailable to ``sys.stderr``
(this argument is ignored on Windows).
If echo free input is unavailable getpass() falls back to printing
a warning message to *stream* and reading from ``sys.stdin`` and
issuing a :exc:`GetPassWarning`.
Availability: Macintosh, Unix, Windows.
.. versionchanged:: 2.6
On Unix it defaults to using /dev/tty before falling back
to ``sys.stdin`` and ``sys.stderr``.
.. note::
If you call getpass from within IDLE, the input may be done in the
terminal you launched IDLE from rather than the idle window itself.
.. exception:: GetPassWarning
A :exc:`UserWarning` subclass issued when password input may be echoed.
.. function:: getuser()

View File

@ -222,7 +222,7 @@ I/O Base Classes
.. method:: fileno()
Return the underlying file descriptor (an integer) of the stream, if it
Return the underlying file descriptor (an integer) of the stream if it
exists. An :exc:`IOError` is raised if the IO object does not use a file
descriptor.
@ -233,18 +233,18 @@ I/O Base Classes
.. method:: isatty()
Returns ``True`` if the stream is interactive (i.e., connected to
Return ``True`` if the stream is interactive (i.e., connected to
a terminal/tty device).
.. method:: readable()
Returns ``True`` if the stream can be read from. If False,
:meth:`read` will raise :exc:`IOError`.
Return ``True`` if the stream can be read from. If False, :meth:`read`
will raise :exc:`IOError`.
.. method:: readline([limit])
Reads and returns one line from the stream. If *limit* is
specified, at most *limit* bytes will be read.
Read and return one line from the stream. If *limit* is specified, at
most *limit* bytes will be read.
The line terminator is always ``b'\n'`` for binary files; for text files,
the *newlines* argument to :func:`open` can be used to select the line
@ -252,9 +252,9 @@ I/O Base Classes
.. method:: readlines([hint])
Returns a list of lines from the stream. *hint* can be specified to
control the number of lines read: no more lines will be read if the total
size (in bytes/characters) of all lines so far exceeds *hint*.
Read and return a list of lines from the stream. *hint* can be specified
to control the number of lines read: no more lines will be read if the
total size (in bytes/characters) of all lines so far exceeds *hint*.
.. method:: seek(offset[, whence])
@ -266,33 +266,32 @@ I/O Base Classes
* ``1`` -- current stream position; *offset* may be negative
* ``2`` -- end of the stream; *offset* is usually negative
Returns the new absolute position.
Return the new absolute position.
.. method:: seekable()
Returns ``True`` if the stream supports random access. If
``False``, :meth:`seek`, :meth:`tell` and :meth:`truncate` will
raise :exc:`IOError`.
Return ``True`` if the stream supports random access. If ``False``,
:meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
.. method:: tell()
Returns the current stream position.
Return the current stream position.
.. method:: truncate([size])
Truncates the file to at most *size* bytes. *size* defaults to the current
Truncate the file to at most *size* bytes. *size* defaults to the current
file position, as returned by :meth:`tell`.
.. method:: writable()
Returns ``True`` if the stream supports writing. If ``False``,
Return ``True`` if the stream supports writing. If ``False``,
:meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
.. method:: writelines(lines)
Writes a list of lines to the stream. Line separators are not
added, so it is usual for each of the lines provided to have a
line separator at the end.
Write a list of lines to the stream. Line separators are not added, so it
is usual for each of the lines provided to have a line separator at the
end.
.. class:: RawIOBase
@ -305,27 +304,26 @@ I/O Base Classes
.. method:: read([n])
Reads and returns all the bytes from the stream until EOF, or if *n* is
specified, up to *n* bytes. An empty bytes object is returned on EOF;
``None`` is returned if the object is set not to block and has no data to
read.
Read and return all the bytes from the stream until EOF, or if *n* is
specified, up to *n* bytes. Only one system call is ever made. An empty
bytes object is returned on EOF; ``None`` is returned if the object is set
not to block and has no data to read.
.. method:: readall()
Reads and returns all the bytes from the stream until EOF, using
multiple calls to the stream if necessary.
Read and return all the bytes from the stream until EOF, using multiple
calls to the stream if necessary.
.. method:: readinto(b)
Reads up to len(b) bytes into bytearray *b* and returns the number
of bytes read.
Read up to len(b) bytes into bytearray *b* and return the number of bytes
read.
.. method:: write(b)
Writes the given bytes or bytearray object, *b*, to the underlying
raw stream and returns the number of bytes written (never less
than ``len(b)``, since if the write fails an :exc:`IOError` will
be raised).
Write the given bytes or bytearray object, *b*, to the underlying raw
stream and return the number of bytes written (This is never less than
``len(b)``, since if the write fails, an :exc:`IOError` will be raised).
Raw File I/O
@ -352,22 +350,21 @@ Raw File I/O
.. attribute:: name
The file name.
The file name. This is the file descriptor of the file when no name is
given in the constructor.
.. method:: read([n])
Reads and returns at most *n* bytes. Only one system call is made, so
it is possible that less data than was requested is returned. Call
:func:`len` on the returned bytes object to see how many bytes
were actually returned (In non-blocking mode, ``None`` is returned
when no data is available.)
Read and return at most *n* bytes. Only one system call is made, so it is
possible that less data than was requested is returned. Use :func:`len`
on the returned bytes object to see how many bytes were actually returned.
(In non-blocking mode, ``None`` is returned when no data is available.)
.. method:: readall()
Reads and returns the entire file's contents in a single bytes
object. As much as immediately available is returned in
non-blocking mode. If the EOF has been reached, ``b''`` is
returned.
Read and return the entire file's contents in a single bytes object. As
much as immediately available is returned in non-blocking mode. If the
EOF has been reached, ``b''`` is returned.
.. method:: write(b)
@ -405,7 +402,7 @@ Buffered Streams
.. method:: read([n])
Reads and returns up to *n* bytes. If the argument is omitted, ``None``, or
Read and return up to *n* bytes. If the argument is omitted, ``None``, or
negative, data is read and returned until EOF is reached. An empty bytes
object is returned if the stream is already at EOF.
@ -420,7 +417,7 @@ Buffered Streams
.. method:: readinto(b)
Reads up to len(b) bytes into bytearray *b* and returns the number of bytes
Read up to len(b) bytes into bytearray *b* and return the number of bytes
read.
Like :meth:`read`, multiple reads may be issued to the underlying raw
@ -431,10 +428,9 @@ Buffered Streams
.. method:: write(b)
Writes the given bytes or bytearray object, *b*, to the underlying
raw stream and returns the number of bytes written (never less than
``len(b)``, since if the write fails an :exc:`IOError` will
be raised).
Write the given bytes or bytearray object, *b*, to the underlying raw
stream and return the number of bytes written (never less than ``len(b)``,
since if the write fails an :exc:`IOError` will be raised).
A :exc:`BlockingIOError` is raised if the buffer is full, and the
underlying raw stream cannot accept more data at the moment.
@ -452,8 +448,7 @@ Buffered Streams
.. method:: getvalue()
Returns a bytes object containing the entire contents of the
buffer.
Return ``bytes`` containing the entire contents of the buffer.
.. method:: read1()
@ -461,8 +456,8 @@ Buffered Streams
.. method:: truncate([size])
Truncates the buffer to at most *size* bytes. *size* defaults to the current
stream position, as returned by :meth:`tell`.
Truncate the buffer to at most *size* bytes. *size* defaults to the
current stream position, as returned by :meth:`tell`.
.. class:: BufferedReader(raw[, buffer_size])
@ -479,20 +474,20 @@ Buffered Streams
.. method:: peek([n])
Returns 1 (or *n* if specified) bytes from a buffer without
advancing the position. Only a single read on the raw stream is done to
satisfy the call. The number of bytes returned may be less than
requested since at most all the buffer's bytes from the current
position to the end are returned.
Return 1 (or *n* if specified) bytes from a buffer without advancing the
position. Only a single read on the raw stream is done to satisfy the
call. The number of bytes returned may be less than requested since at
most all the buffer's bytes from the current position to the end are
returned.
.. method:: read([n])
Reads and returns *n* bytes, or if *n* is not given or negative, until EOF
Read and return *n* bytes, or if *n* is not given or negative, until EOF
or if the read call would block in non-blocking mode.
.. method:: read1(n)
Reads and returns up to *n* bytes with only one call on the raw stream. If
Read and return up to *n* bytes with only one call on the raw stream. If
at least one byte is buffered, only buffered bytes are returned.
Otherwise, one raw stream read call is made.
@ -517,9 +512,9 @@ Buffered Streams
.. method:: write(b)
Writes the bytes or bytearray object, *b*, onto the raw stream and
returns the number of bytes written. A :exc:`BlockingIOError` is
raised when the raw stream blocks.
Write the bytes or bytearray object, *b*, onto the raw stream and return
the number of bytes written. A :exc:`BlockingIOError` is raised when the
raw stream blocks.
.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]])
@ -576,18 +571,18 @@ Text I/O
.. method:: read(n)
Reads and returns at most *n* characters from the stream as a
single :class:`str`. If *n* is negative or ``None``, reads to EOF.
Read and return at most *n* characters from the stream as a single
:class:`str`. If *n* is negative or ``None``, reads to EOF.
.. method:: readline()
Reads until newline or EOF and returns a single :class:`str`. If
the stream is already at EOF, an empty string is returned.
Read until newline or EOF and return a single ``str``. If the stream is
already at EOF, an empty string is returned.
.. method:: write(s)
Writes the string *s* to the stream and returns the number of
characters written.
Write the string *s* to the stream and return the number of characters
written.
.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
@ -646,7 +641,7 @@ Text I/O
.. method:: getvalue()
Returns a :class:`str` containing the entire contents of the buffer.
Return a ``str`` containing the entire contents of the buffer.
.. class:: IncrementalNewlineDecoder

View File

@ -1633,7 +1633,7 @@ arguments::
[...]
parser.add_option("-c", "--callback",
action="callback", callback=varargs)
action="callback", callback=vararg_callback)
The main weakness with this particular implementation is that negative numbers
in the arguments following ``"-c"`` will be interpreted as further options

View File

@ -42,13 +42,13 @@ This module provides functions to manipulate packages:
Get a resource from a package.
This is a wrapper round the PEP 302 loader :func:`get_data` API. The package
This is a wrapper for the PEP 302 loader :func:`get_data` API. The package
argument should be the name of a package, in standard module format
(foo.bar). The resource argument should be in the form of a relative
filename, using ``/`` as the path separator. The parent directory name
``..`` is not allowed, and nor is a rooted name (starting with a ``/``).
The function returns a binary string, which is the contents of the
The function returns a binary string that is the contents of the
specified resource.
For packages located in the filesystem, which have already been imported,

View File

@ -7,75 +7,75 @@
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
The :mod:`pyclbr` can be used to determine some limited information about the
classes, methods and top-level functions defined in a module. The information
provided is sufficient to implement a traditional three-pane class browser. The
information is extracted from the source code rather than by importing the
module, so this module is safe to use with untrusted source code. This
restriction makes it impossible to use this module with modules not implemented
in Python, including many standard and optional extension modules.
The :mod:`pyclbr` module can be used to determine some limited information
about the classes, methods and top-level functions defined in a module. The
information provided is sufficient to implement a traditional three-pane
class browser. The information is extracted from the source code rather
than by importing the module, so this module is safe to use with untrusted
code. This restriction makes it impossible to use this module with modules
not implemented in Python, including all standard and optional extension
modules.
.. function:: readmodule(module[, path])
.. function:: readmodule(module[, path=None])
Read a module and return a dictionary mapping class names to class descriptor
objects. The parameter *module* should be the name of a module as a string;
it may be the name of a module within a package. The *path* parameter should
be a sequence, and is used to augment the value of ``sys.path``, which is
used to locate module source code.
.. The 'inpackage' parameter appears to be for internal use only....
Read a module and return a dictionary mapping class names to class
descriptor objects. The parameter *module* should be the name of a
module as a string; it may be the name of a module within a package. The
*path* parameter should be a sequence, and is used to augment the value
of ``sys.path``, which is used to locate module source code.
.. function:: readmodule_ex(module[, path])
.. function:: readmodule_ex(module[, path=None])
Like :func:`readmodule`, but the returned dictionary, in addition to mapping
class names to class descriptor objects, also maps top-level function names to
function descriptor objects. Moreover, if the module being read is a package,
the key ``'__path__'`` in the returned dictionary has as its value a list which
contains the package search path.
.. The 'inpackage' parameter appears to be for internal use only....
Like :func:`readmodule`, but the returned dictionary, in addition to
mapping class names to class descriptor objects, also maps top-level
function names to function descriptor objects. Moreover, if the module
being read is a package, the key ``'__path__'`` in the returned
dictionary has as its value a list which contains the package search
path.
.. _pyclbr-class-objects:
Class Descriptor Objects
------------------------
Class Objects
-------------
The class descriptor objects used as values in the dictionary returned by
:func:`readmodule` and :func:`readmodule_ex` provide the following data members:
The :class:`Class` objects used as values in the dictionary returned by
:func:`readmodule` and :func:`readmodule_ex` provide the following data
members:
.. attribute:: class_descriptor.module
.. attribute:: Class.module
The name of the module defining the class described by the class descriptor.
.. attribute:: class_descriptor.name
.. attribute:: Class.name
The name of the class.
.. attribute:: class_descriptor.super
.. attribute:: Class.super
A list of class descriptors which describe the immediate base classes of the
class being described. Classes which are named as superclasses but which are
not discoverable by :func:`readmodule` are listed as a string with the class
name instead of class descriptors.
A list of :class:`Class` objects which describe the immediate base
classes of the class being described. Classes which are named as
superclasses but which are not discoverable by :func:`readmodule` are
listed as a string with the class name instead of as :class:`Class`
objects.
.. attribute:: class_descriptor.methods
.. attribute:: Class.methods
A dictionary mapping method names to line numbers.
.. attribute:: class_descriptor.file
.. attribute:: Class.file
Name of the file containing the ``class`` statement defining the class.
.. attribute:: class_descriptor.lineno
.. attribute:: Class.lineno
The line number of the ``class`` statement within the file named by
:attr:`file`.
@ -83,30 +83,31 @@ The class descriptor objects used as values in the dictionary returned by
.. _pyclbr-function-objects:
Function Descriptor Objects
---------------------------
Function Objects
----------------
The function descriptor objects used as values in the dictionary returned by
The :class:`Function` objects used as values in the dictionary returned by
:func:`readmodule_ex` provide the following data members:
.. attribute:: function_descriptor.module
.. attribute:: Function.module
The name of the module defining the function described by the function
descriptor.
.. attribute:: function_descriptor.name
.. attribute:: Function.name
The name of the function.
.. attribute:: function_descriptor.file
.. attribute:: Function.file
Name of the file containing the ``def`` statement defining the function.
.. attribute:: function_descriptor.lineno
.. attribute:: Function.lineno
The line number of the ``def`` statement within the file named by :attr:`file`.
The line number of the ``def`` statement within the file named by
:attr:`file`.

View File

@ -3,7 +3,8 @@
=============================================
.. module:: robotparser
:synopsis: Loads a robots.txt file and answers questions about fetchability of other URLs.
:synopsis: Loads a robots.txt file and answers questions about
fetchability of other URLs.
.. sectionauthor:: Skip Montanaro <skip@pobox.com>
@ -21,8 +22,8 @@ structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html.
.. class:: RobotFileParser()
This class provides a set of methods to read, parse and answer questions about a
single :file:`robots.txt` file.
This class provides a set of methods to read, parse and answer questions
about a single :file:`robots.txt` file.
.. method:: set_url(url)
@ -42,20 +43,22 @@ structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html.
.. method:: can_fetch(useragent, url)
Returns ``True`` if the *useragent* is allowed to fetch the *url* according to
the rules contained in the parsed :file:`robots.txt` file.
Returns ``True`` if the *useragent* is allowed to fetch the *url*
according to the rules contained in the parsed :file:`robots.txt`
file.
.. method:: mtime()
Returns the time the ``robots.txt`` file was last fetched. This is useful for
long-running web spiders that need to check for new ``robots.txt`` files
periodically.
Returns the time the ``robots.txt`` file was last fetched. This is
useful for long-running web spiders that need to check for new
``robots.txt`` files periodically.
.. method:: modified()
Sets the time the ``robots.txt`` file was last fetched to the current time.
Sets the time the ``robots.txt`` file was last fetched to the current
time.
The following example demonstrates basic use of the RobotFileParser class. ::

View File

@ -7,39 +7,40 @@
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
The :mod:`SimpleHTTPServer` module defines a request-handler class,
interface-compatible with :class:`BaseHTTPServer.BaseHTTPRequestHandler`, that
serves files only from a base directory.
The :mod:`SimpleHTTPServer` module defines a single class,
:class:`SimpleHTTPRequestHandler`, which is interface-compatible with
:class:`BaseHTTPServer.BaseHTTPRequestHandler`.
The :mod:`SimpleHTTPServer` module defines the following class:
.. class:: SimpleHTTPRequestHandler(request, client_address, server)
This class is used to serve files from the current directory and below, directly
This class serves files from the current directory and below, directly
mapping the directory structure to HTTP requests.
A lot of the work, such as parsing the request, is done by the base class
:class:`BaseHTTPServer.BaseHTTPRequestHandler`. This class implements the
:func:`do_GET` and :func:`do_HEAD` functions.
The :class:`SimpleHTTPRequestHandler` defines the following member variables:
The following are defined as class-level attributes of
:class:`SimpleHTTPRequestHandler`:
.. attribute:: server_version
This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
defined in the module.
This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
defined at the module level.
.. attribute:: extensions_map
A dictionary mapping suffixes into MIME types. The default is signified by
an empty string, and is considered to be ``application/octet-stream``. The
mapping is used case-insensitively, and so should contain only lower-cased
keys.
A dictionary mapping suffixes into MIME types. The default is
signified by an empty string, and is considered to be
``application/octet-stream``. The mapping is used case-insensitively,
and so should contain only lower-cased keys.
The :class:`SimpleHTTPRequestHandler` defines the following methods:
The :class:`SimpleHTTPRequestHandler` class defines the following methods:
.. method:: do_HEAD()

View File

@ -765,7 +765,7 @@ The first two examples support IPv4 only. ::
# Echo server program
import socket
HOST = '' # Symbolic name meaning the local host
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))

View File

@ -112,10 +112,11 @@ Module functions and constants
:func:`connect` function.
Setting it makes the :mod:`sqlite3` module parse the declared type for each
column it returns. It will parse out the first word of the declared type, i. e.
for "integer primary key", it will parse out "integer". Then for that column, it
will look into the converters dictionary and use the converter function
registered for that type there. Converter names are case-sensitive!
column it returns. It will parse out the first word of the declared type,
i. e. for "integer primary key", it will parse out "integer", or for
"number(10)" it will parse out "number". Then for that column, it will look
into the converters dictionary and use the converter function registered for
that type there.
.. data:: PARSE_COLNAMES
@ -654,10 +655,6 @@ and constructs a :class:`Point` object from it.
Converter functions **always** get called with a string, no matter under which
data type you sent the value to SQLite.
.. note::
Converter names are looked up in a case-sensitive manner.
::
def convert_point(s):

View File

@ -216,7 +216,7 @@ Instances of the :class:`Popen` class have the following methods:
.. method:: Popen.terminate()
Stop the child. On Posix OSs the method sends SIGTERM to the
child. On Windows the Win32 API function TerminateProcess is called
child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
to stop the child.

View File

@ -379,17 +379,17 @@ always available.
*platform* may be one of the following values:
+-----------------------------------------+-----------------------+
| Constant | Platform |
+=========================================+=======================+
| :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
+-----------------------------------------+-----------------------+
| :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
+-----------------------------------------+-----------------------+
| :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP |
+-----------------------------------------+-----------------------+
| :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
+-----------------------------------------+-----------------------+
+-----------------------------------------+-------------------------+
| Constant | Platform |
+=========================================+=========================+
| :const:`0 (VER_PLATFORM_WIN32s)` | Win32s on Windows 3.1 |
+-----------------------------------------+-------------------------+
| :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME |
+-----------------------------------------+-------------------------+
| :const:`2 (VER_PLATFORM_WIN32_NT)` | Windows NT/2000/XP/x64 |
+-----------------------------------------+-------------------------+
| :const:`3 (VER_PLATFORM_WIN32_CE)` | Windows CE |
+-----------------------------------------+-------------------------+
This function wraps the Win32 :cfunc:`GetVersionEx` function; see the Microsoft
documentation for more information about these fields.

View File

@ -23,147 +23,155 @@ insecure :func:`mktemp` function. Temporary file names created by this module
no longer contain the process ID; instead a string of six random characters is
used.
Also, all the user-callable functions now take additional arguments which allow
direct control over the location and name of temporary files. It is no longer
necessary to use the global *tempdir* and *template* variables. To maintain
backward compatibility, the argument order is somewhat odd; it is recommended to
use keyword arguments for clarity.
Also, all the user-callable functions now take additional arguments which
allow direct control over the location and name of temporary files. It is
no longer necessary to use the global *tempdir* and *template* variables.
To maintain backward compatibility, the argument order is somewhat odd; it
is recommended to use keyword arguments for clarity.
The module defines the following user-callable functions:
.. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]])
.. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])
Return a file-like object that can be used as a temporary storage
area. The file is created using :func:`mkstemp`. It will be destroyed as soon
Return a file-like object that can be used as a temporary storage area.
The file is created using :func:`mkstemp`. It will be destroyed as soon
as it is closed (including an implicit close when the object is garbage
collected). Under Unix, the directory entry for the file is removed immediately
after the file is created. Other platforms do not support this; your code
should not rely on a temporary file created using this function having or not
having a visible name in the file system.
collected). Under Unix, the directory entry for the file is removed
immediately after the file is created. Other platforms do not support
this; your code should not rely on a temporary file created using this
function having or not having a visible name in the file system.
The *mode* parameter defaults to ``'w+b'`` so that the file created can be read
and written without being closed. Binary mode is used so that it behaves
consistently on all platforms without regard for the data that is stored.
*bufsize* defaults to ``-1``, meaning that the operating system default is used.
The *mode* parameter defaults to ``'w+b'`` so that the file created can
be read and written without being closed. Binary mode is used so that it
behaves consistently on all platforms without regard for the data that is
stored. *bufsize* defaults to ``-1``, meaning that the operating system
default is used.
The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
The returned object is a true file object on POSIX platforms. On other
platforms, it is a file-like object whose :attr:`file` attribute is the
underlying true file object. This file-like object can be used in a :keyword:`with`
statement, just like a normal file.
.. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir[, delete]]]]]])
This function operates exactly as :func:`TemporaryFile` does, except that the
file is guaranteed to have a visible name in the file system (on Unix, the
directory entry is not unlinked). That name can be retrieved from the
:attr:`name` member of the file object. Whether the name can be used to open
the file a second time, while the named temporary file is still open, varies
across platforms (it can be so used on Unix; it cannot on Windows NT or later).
If *delete* is true (the default), the file is deleted as soon as it is closed.
The returned object is always a file-like object whose :attr:`file` attribute
is the underlying true file object. This file-like object can be used in a :keyword:`with`
statement, just like a normal file.
.. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]]])
This function operates exactly as :func:`TemporaryFile` does, except that data
is spooled in memory until the file size exceeds *max_size*, or until the file's
:func:`fileno` method is called, at which point the contents are written to disk
and operation proceeds as with :func:`TemporaryFile`.
The resulting file has one additional method, :func:`rollover`, which causes the
file to roll over to an on-disk file regardless of its size.
The returned object is a file-like object whose :attr:`_file` attribute
is either a :class:`StringIO` object or a true file object, depending on
whether :func:`rollover` has been called. This file-like object can be used in a
underlying true file object. This file-like object can be used in a
:keyword:`with` statement, just like a normal file.
.. function:: mkstemp([suffix[, prefix[, dir[, text]]]])
.. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])
Creates a temporary file in the most secure manner possible. There are no
race conditions in the file's creation, assuming that the platform properly
implements the :const:`os.O_EXCL` flag for :func:`os.open`. The file is
readable and writable only by the creating user ID. If the platform uses
permission bits to indicate whether a file is executable, the file is
executable by no one. The file descriptor is not inherited by child
processes.
Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible for
deleting the temporary file when done with it.
If *suffix* is specified, the file name will end with that suffix, otherwise
there will be no suffix. :func:`mkstemp` does not put a dot between the file
name and the suffix; if you need one, put it at the beginning of *suffix*.
If *prefix* is specified, the file name will begin with that prefix; otherwise,
a default prefix is used.
If *dir* is specified, the file will be created in that directory; otherwise,
a default directory is used. The default directory is chosen from a
platform-dependent list, but the user of the application can control the
directory location by setting the *TMPDIR*, *TEMP* or *TMP* environment
variables. There is thus no guarantee that the generated filename will have
any nice properties, such as not requiring quoting when passed to external
commands via ``os.popen()``.
If *text* is specified, it indicates whether to open the file in binary mode
(the default) or text mode. On some platforms, this makes no difference.
:func:`mkstemp` returns a tuple containing an OS-level handle to an open file
(as would be returned by :func:`os.open`) and the absolute pathname of that
file, in that order.
This function operates exactly as :func:`TemporaryFile` does, except that
the file is guaranteed to have a visible name in the file system (on
Unix, the directory entry is not unlinked). That name can be retrieved
from the :attr:`name` member of the file object. Whether the name can be
used to open the file a second time, while the named temporary file is
still open, varies across platforms (it can be so used on Unix; it cannot
on Windows NT or later). If *delete* is true (the default), the file is
deleted as soon as it is closed.
The returned object is always a file-like object whose :attr:`file`
attribute is the underlying true file object. This file-like object can
be used in a :keyword:`with` statement, just like a normal file.
.. function:: mkdtemp([suffix[, prefix[, dir]]])
.. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]])
Creates a temporary directory in the most secure manner possible. There are no
race conditions in the directory's creation. The directory is readable,
writable, and searchable only by the creating user ID.
This function operates exactly as :func:`TemporaryFile` does, except that
data is spooled in memory until the file size exceeds *max_size*, or
until the file's :func:`fileno` method is called, at which point the
contents are written to disk and operation proceeds as with
:func:`TemporaryFile`.
The user of :func:`mkdtemp` is responsible for deleting the temporary directory
and its contents when done with it.
The resulting file has one additional method, :func:`rollover`, which
causes the file to roll over to an on-disk file regardless of its size.
The *prefix*, *suffix*, and *dir* arguments are the same as for :func:`mkstemp`.
The returned object is a file-like object whose :attr:`_file` attribute
is either a :class:`StringIO` object or a true file object, depending on
whether :func:`rollover` has been called. This file-like object can be
used in a :keyword:`with` statement, just like a normal file.
.. function:: mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])
Creates a temporary file in the most secure manner possible. There are
no race conditions in the file's creation, assuming that the platform
properly implements the :const:`os.O_EXCL` flag for :func:`os.open`. The
file is readable and writable only by the creating user ID. If the
platform uses permission bits to indicate whether a file is executable,
the file is executable by no one. The file descriptor is not inherited
by child processes.
Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
for deleting the temporary file when done with it.
If *suffix* is specified, the file name will end with that suffix,
otherwise there will be no suffix. :func:`mkstemp` does not put a dot
between the file name and the suffix; if you need one, put it at the
beginning of *suffix*.
If *prefix* is specified, the file name will begin with that prefix;
otherwise, a default prefix is used.
If *dir* is specified, the file will be created in that directory;
otherwise, a default directory is used. The default directory is chosen
from a platform-dependent list, but the user of the application can
control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
environment variables. There is thus no guarantee that the generated
filename will have any nice properties, such as not requiring quoting
when passed to external commands via ``os.popen()``.
If *text* is specified, it indicates whether to open the file in binary
mode (the default) or text mode. On some platforms, this makes no
difference.
:func:`mkstemp` returns a tuple containing an OS-level handle to an open
file (as would be returned by :func:`os.open`) and the absolute pathname
of that file, in that order.
.. function:: mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]])
Creates a temporary directory in the most secure manner possible. There
are no race conditions in the directory's creation. The directory is
readable, writable, and searchable only by the creating user ID.
The user of :func:`mkdtemp` is responsible for deleting the temporary
directory and its contents when done with it.
The *prefix*, *suffix*, and *dir* arguments are the same as for
:func:`mkstemp`.
:func:`mkdtemp` returns the absolute pathname of the new directory.
.. function:: mktemp([suffix[, prefix[, dir]]])
.. function:: mktemp([suffix=''[, prefix='tmp'[, dir=None]]])
.. deprecated:: 2.3
Use :func:`mkstemp` instead.
Return an absolute pathname of a file that did not exist at the time the call is
made. The *prefix*, *suffix*, and *dir* arguments are the same as for
:func:`mkstemp`.
Return an absolute pathname of a file that did not exist at the time the
call is made. The *prefix*, *suffix*, and *dir* arguments are the same
as for :func:`mkstemp`.
.. warning::
Use of this function may introduce a security hole in your program. By the time
you get around to doing anything with the file name it returns, someone else may
have beaten you to the punch.
Use of this function may introduce a security hole in your program.
By the time you get around to doing anything with the file name it
returns, someone else may have beaten you to the punch.
The module uses two global variables that tell it how to construct a temporary
name. They are initialized at the first call to any of the functions above.
The caller may change them, but this is discouraged; use the appropriate
function arguments, instead.
The module uses two global variables that tell it how to construct a
temporary name. They are initialized at the first call to any of the
functions above. The caller may change them, but this is discouraged; use
the appropriate function arguments, instead.
.. data:: tempdir
When set to a value other than ``None``, this variable defines the default value
for the *dir* argument to all the functions defined in this module.
When set to a value other than ``None``, this variable defines the
default value for the *dir* argument to all the functions defined in this
module.
If ``tempdir`` is unset or ``None`` at any call to any of the above functions,
Python searches a standard list of directories and sets *tempdir* to the first
one which the calling user can create files in. The list is:
If ``tempdir`` is unset or ``None`` at any call to any of the above
functions, Python searches a standard list of directories and sets
*tempdir* to the first one which the calling user can create files in.
The list is:
#. The directory named by the :envvar:`TMPDIR` environment variable.

View File

@ -260,7 +260,6 @@ Such a working environment for the testing code is called a :dfn:`fixture`.
Often, many small test cases will use the same fixture. In this case, we would
end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
classes such as :class:`DefaultWidgetSizeTestCase`. This is time-consuming and
discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
mechanism::

View File

@ -111,6 +111,14 @@ between conformable Python objects and XML on the wire.
`XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
Describes the XML-RPC protocol extension for introspection.
`XML-RPC Specification <http://www.xmlrpc.com/spec>`_
The official specification.
`Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
Fredrik Lundh's "unofficial errata, intended to clarify certain
details in the XML-RPC specification, as well as hint at
'best practices' to use when designing your own XML-RPC
implementations."
.. _serverproxy-objects:
@ -280,6 +288,11 @@ internal use by the marshalling/unmarshalling code:
Write the XML-RPC base 64 encoding of this binary item to the out stream object.
The encoded data will have newlines every 76 characters as per
`RFC 2045 section 6.8 <http://tools.ietf.org/html/rfc2045#section-6.8>`_,
which was the de facto standard base64 specification when the
XML-RPC spec was written.
It also supports certain of Python's built-in operators through a
:meth:`__cmp__` method.

View File

@ -651,6 +651,14 @@ slots for which no default value is specified, a :exc:`TypeError` exception is
raised. Otherwise, the list of filled slots is used as the argument list for
the call.
.. note::
An implementation may provide builtin functions whose positional parameters do
not have names, even if they are 'named' for the purpose of documentation, and
which therefore cannot be supplied by keyword. In CPython, this is the case for
functions implemented in C that use :cfunc:`PyArg_ParseTuple` to parse their
arguments.
If there are more positional arguments than there are formal parameter slots, a
:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
``*identifier`` is present; in this case, that formal parameter receives a tuple

View File

@ -3,28 +3,28 @@
<p><strong>Parts of the documentation:</strong></p>
<table class="contentstable" align="center"><tr>
<td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("whatsnew/" + version) }}">What's new in Python {{ version }}?</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("whatsnew/" + version) }}">What's new in Python {{ version }}?</a><br/>
<span class="linkdescr">changes since previous major release</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("tutorial/index") }}">Tutorial</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("tutorial/index") }}">Tutorial</a><br/>
<span class="linkdescr">start here</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("using/index") }}">Using Python</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("using/index") }}">Using Python</a><br/>
<span class="linkdescr">how to use Python on different platforms</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("reference/index") }}">Language Reference</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("reference/index") }}">Language Reference</a><br/>
<span class="linkdescr">describes syntax and language elements</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("library/index") }}">Library Reference</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("library/index") }}">Library Reference</a><br/>
<span class="linkdescr">keep this under your pillow</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("howto/index") }}">Python HOWTOs</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("howto/index") }}">Python HOWTOs</a><br/>
<span class="linkdescr">in-depth documents on specific topics</span></p>
</td><td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("extending/index") }}">Extending and Embedding</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("extending/index") }}">Extending and Embedding</a><br/>
<span class="linkdescr">tutorial for C/C++ programmers</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("c-api/index") }}">Python/C API</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("c-api/index") }}">Python/C API</a><br/>
<span class="linkdescr">reference for C/C++ programmers</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("install/index") }}">Installing Python Modules</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("install/index") }}">Installing Python Modules</a><br/>
<span class="linkdescr">information for installers &amp; sys-admins</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("distutils/index") }}">Distributing Python Modules</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("distutils/index") }}">Distributing Python Modules</a><br/>
<span class="linkdescr">sharing modules with others</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("documenting/index") }}">Documenting Python</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("documenting/index") }}">Documenting Python</a><br/>
<span class="linkdescr">guide for documentation authors</span></p>
</td></tr>
</table>
@ -32,16 +32,16 @@
<p><strong>Indices and tables:</strong></p>
<table class="contentstable" align="center"><tr>
<td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("modindex") }}">Global Module Index</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("modindex") }}">Global Module Index</a><br/>
<span class="linkdescr">quick access to all modules</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("genindex") }}">General Index</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("genindex") }}">General Index</a><br/>
<span class="linkdescr">all functions, classes, terms</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("glossary") }}">Glossary</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("glossary") }}">Glossary</a><br/>
<span class="linkdescr">the most important terms explained</span></p>
</td><td width="50%">
<p class="biglink"><a class="biglink" href="{{ pathto("search") }}">Search page</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("search") }}">Search page</a><br/>
<span class="linkdescr">search this documentation</span></p>
<p class="biglink"><a class="biglink" href="{{ pathto("contents") }}">Complete Table of Contents</a><br>
<p class="biglink"><a class="biglink" href="{{ pathto("contents") }}">Complete Table of Contents</a><br/>
<span class="linkdescr">lists all sections and subsections</span></p>
</td></tr>
</table>

View File

@ -28,20 +28,25 @@ The most common use case is, of course, a simple invocation of a script::
python myscript.py
.. _using-on-interface-options:
Interface options
~~~~~~~~~~~~~~~~~
The interpreter interface resembles that of the UNIX shell:
The interpreter interface resembles that of the UNIX shell, but provides some
additional methods of invocation:
* When called with standard input connected to a tty device, it prompts for
commands and executes them until an EOF (an end-of-file character, you can
produce that with *Ctrl-D* on UNIX or *Ctrl-Z, Enter* on Windows) is read.
* When called with a file name argument or with a file as standard input, it
reads and executes a script from that file.
* When called with a directory name argument, it reads and executes an
appropriately named script from that directory.
* When called with ``-c command``, it executes the Python statement(s) given as
*command*. Here *command* may contain multiple statements separated by
newlines. Leading whitespace is significant in Python statements!
* When called with ``-m module-name``, the given module is searched on the
* When called with ``-m module-name``, the given module is located on the
Python module path and executed as a script.
In non-interactive mode, the entire input is parsed before it is executed.
@ -58,25 +63,31 @@ source.
normal module code.
If this option is given, the first element of :data:`sys.argv` will be
``"-c"``.
``"-c"`` and the current directory will be added to the start of
:data:`sys.path` (allowing modules in that directory to be imported as top
level modules).
.. cmdoption:: -m <module-name>
Search :data:`sys.path` for the named module and run the corresponding module
file as if it were executed with ``python modulefile.py`` as a script.
Search :data:`sys.path` for the named module and execute its contents as
the :mod:`__main__` module.
Since the argument is a *module* name, you must not give a file extension
(``.py``). However, the ``module-name`` does not have to be a valid Python
identifer (e.g. you can use a file name including a hyphen).
(``.py``). The ``module-name`` should be a valid Python module name, but
the implementation may not always enforce this (e.g. it may allow you to
use a name that includes a hyphen).
.. note::
This option cannot be used with builtin modules and extension modules
written in C, since they do not have Python module files.
written in C, since they do not have Python module files. However, it
can still be used for precompiled modules, even if the original source
file is not available.
If this option is given, the first element of :data:`sys.argv` will be the
full path to the module file.
full path to the module file. As with the :option:`-c` option, the current
directory will be added to the start of :data:`sys.path`.
Many standard library modules contain code that is invoked on their execution
as a script. An example is the :mod:`timeit` module::
@ -91,30 +102,46 @@ source.
:pep:`338` -- Executing modules as scripts
.. describe:: <script>
Execute the Python code contained in *script*, which must be an (absolute or
relative) file name.
If this option is given, the first element of :data:`sys.argv` will be the
script file name as given on the command line.
.. describe:: -
Read commands from standard input (:data:`sys.stdin`). If standard input is
a terminal, :option:`-i` is implied.
If this option is given, the first element of :data:`sys.argv` will be
``"-"``.
``"-"`` and the current directory will be added to the start of
:data:`sys.path`.
.. describe:: <script>
Execute the Python code contained in *script*, which must be a filesystem
path (absolute or relative) referring to either a Python file, a directory
containing a ``__main__.py`` file, or a zipfile containing a
``__main__.py`` file.
If this option is given, the first element of :data:`sys.argv` will be the
script name as given on the command line.
If the script name refers directly to a Python file, the directory
containing that file is added to the start of :data:`sys.path`, and the
file is executed as the :mod:`__main__` module.
If the script name refers to a directory or zipfile, the script name is
added to the start of :data:`sys.path` and the ``__main__.py`` file in
that location is executed as the :mod:`__main__` module.
.. versionchanged:: 2.5
Directories and zipfiles containing a ``__main__.py`` file at the top
level are now considered valid Python scripts.
If no interface option is given, :option:`-i` is implied, ``sys.argv[0]`` is
an empty string (``""``) and the current directory will be added to the
start of :data:`sys.path`.
.. seealso::
:ref:`tut-invoking`
If no script name is given, ``sys.argv[0]`` is an empty string (``""``).
Generic options
~~~~~~~~~~~~~~~
@ -276,6 +303,7 @@ Miscellaneous options
thus equivalent to an omitted line number.
.. seealso::
:mod:`warnings` -- the warnings module
:pep:`230` -- Warning framework
@ -313,14 +341,19 @@ These environment variables influence Python's behavior.
the shell's :envvar:`PATH`: one or more directory pathnames separated by
:data:`os.pathsep` (e.g. colons on Unix or semicolons on Windows).
Non-existent directories are silently ignored.
In addition to normal directories, individual :envvar:`PYTHONPATH` entries
may refer to zipfiles containing pure Python modules (in either source or
compiled form). Extension modules cannot be imported from zipfiles.
The default search path is installation dependent, but generally begins with
:file:`{prefix}/lib/python{version}`` (see :envvar:`PYTHONHOME` above). It
is *always* appended to :envvar:`PYTHONPATH`.
If a script argument is given, the directory containing the script is
inserted in the path in front of :envvar:`PYTHONPATH`. The search path can
be manipulated from within a Python program as the variable :data:`sys.path`.
An additional directory will be inserted in the search path in front of
:envvar:`PYTHONPATH` as described above under
:ref:`using-on-interface-options`. The search path can be manipulated from
within a Python program as the variable :data:`sys.path`.
.. envvar:: PYTHONSTARTUP
@ -406,7 +439,7 @@ if Python was configured with the :option:`--with-pydebug` build option.
.. envvar:: PYTHONTHREADDEBUG
If set, Python will print debug threading debug info.
If set, Python will print threading debug info.
.. versionchanged:: 2.6
Previously, this variable was called ``THREADDEBUG``.

View File

@ -119,7 +119,7 @@ While 2.6 was being developed, the Python development process
underwent two significant changes: the developer group
switched from SourceForge's issue tracker to a customized
Roundup installation, and the documentation was converted from
LaTeX to reStructured Text.
LaTeX to reStructuredText.
New Issue Tracker: Roundup
@ -137,7 +137,7 @@ SourceForge. Four different trackers were examined: Atlassian's `Jira
<http://www.atlassian.com/software/jira/>`__,
`Launchpad <http://www.launchpad.net>`__,
`Roundup <http://roundup.sourceforge.net/>`__, and
Trac <http://trac.edgewall.org/>`__.
`Trac <http://trac.edgewall.org/>`__.
The committee eventually settled on Jira
and Roundup as the two candidates. Jira is a commercial product that
offers a no-cost hosted instance to free-software projects; Roundup
@ -171,7 +171,7 @@ http://svn.python.org/view/tracker/importer/.
Roundup downloads and documentation.
New Documentation Format: ReStructured Text Using Sphinx
New Documentation Format: reStructuredText Using Sphinx
-----------------------------------------------------------
Since the Python project's inception around 1989, the documentation
@ -195,7 +195,7 @@ and no one pursued the task to completion.
During the 2.6 development cycle, Georg Brandl put a substantial
effort into building a new toolchain for processing the documentation.
The resulting package is called Sphinx, and is available from
http://sphinx.pocoo.org/. The input format is reStructured Text, a
http://sphinx.pocoo.org/. The input format is reStructuredText, a
markup commonly used in the Python community that supports custom
extensions and directives. Sphinx concentrates on HTML output,
producing attractively styled and modern HTML, though printed output
@ -211,7 +211,7 @@ standalone package that can be used in documenting other projects.
Documentation and code for the Sphinx toolchain.
`Docutils <http://docutils.sf.net>`__
The underlying reStructured Text parser and toolset.
The underlying reStructuredText parser and toolset.
PEP 343: The 'with' statement
@ -734,7 +734,8 @@ and it also supports the ``b''`` notation.
There's also a ``__future__`` import that causes all string literals
to become Unicode strings. This means that ``\u`` escape sequences
can be used to include Unicode characters.
can be used to include Unicode characters::
from __future__ import unicode_literals
@ -744,6 +745,7 @@ can be used to include Unicode characters.
print len(s) # 12 Unicode characters
.. seealso::
:pep:`3112` - Bytes literals in Python 3000
@ -1383,6 +1385,11 @@ Here are all of the changes that Python 2.6 makes to the core Python language.
Optimizations
-------------
* The :mod:`warnings` module has been rewritten in C. This makes
it possible to invoke warnings from the parser, and may also
make the interpreter's startup faster.
(Contributed by Neal Norwitz and Brett Cannon; :issue:`1631171`.)
* Type objects now have a cache of methods that can reduce
the amount of work required to find the correct method implementation
for a particular class; once cached, the interpreter doesn't need to
@ -1401,7 +1408,7 @@ Optimizations
built-in types. This speeds up checking if an object is a subclass of one of
these types. (Contributed by Neal Norwitz.)
* Unicode strings now uses faster code for detecting
* Unicode strings now use faster code for detecting
whitespace and line breaks; this speeds up the :meth:`split` method
by about 25% and :meth:`splitlines` by 35%.
(Contributed by Antoine Pitrou.) Memory usage is reduced
@ -1801,6 +1808,24 @@ complete list of changes, or look through the CVS logs for all the details.
opcodes, returning a shorter pickle that contains the same data structure.
(Contributed by Raymond Hettinger.)
* A :func:`get_data` function was added to the :mod:`pkgutil`
module that returns the contents of resource files included
with an installed Python package. For example::
>>> import pkgutil
>>> pkgutil.get_data('test', 'exception_hierarchy.txt')
'BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
...'
>>>
(Contributed by Paul Moore; :issue:`2439`.)
* New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags`
are wrappers for the corresponding system calls (where they're available).
Constants for the flag values are defined in the :mod:`stat` module; some
@ -1934,6 +1959,13 @@ complete list of changes, or look through the CVS logs for all the details.
* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type,
using the format character ``'?'``.
(Contributed by David Remahl.)
* The :class:`Popen` objects provided by the :mod:`subprocess` module
now have :meth:`terminate`, :meth:`kill`, and :meth:`send_signal` methods.
On Windows, :meth:`send_signal` only supports the :const:`SIGTERM`
signal, and all these methods are aliases for the Win32 API function
:cfunc:`TerminateProcess`.
(Contributed by Christian Heimes.)
* A new variable in the :mod:`sys` module,
:attr:`float_info`, is an object
@ -2088,6 +2120,14 @@ complete list of changes, or look through the CVS logs for all the details.
information. (Contributed by Alan McIntyre as part of his
project for Google's Summer of Code 2007.)
* The :mod:`xmlrpclib` module no longer automatically converts
:class:`datetime.date` and :class:`datetime.time` to the
:class:`xmlrpclib.DateTime` type; the conversion semantics were
not necessarily correct for all applications. Code using
:mod:`xmlrpclib` should convert :class:`date` and :class:`time`
instances. (:issue:`1330538`) The code can also handle
dates before 1900. (Contributed by Ralf Schmitt; :issue:`2014`.)
* The :mod:`zipfile` module's :class:`ZipFile` class now has
:meth:`extract` and :meth:`extractall` methods that will unpack
a single file or all the files in the archive to the current directory, or
@ -2120,17 +2160,12 @@ though it will be removed in Python 3.0.
To use the new module, first you must create a TCP connection in the
usual way and then pass it to the :func:`ssl.wrap_socket` function.
XXX describe parameters.
XXX Can specify if certificate is required, and obtain certificate info
by calling getpeercert method.
XXX Certain features require the OpenSSL package to be installed, notably
the 'openssl' binary.
It's possible to specify whether a certificate is required, and to
obtain certificate info by calling the :meth:`getpeercert` method.
.. seealso::
SSL module documentation.
The documentation for the :mod:`ssl` module.
.. ======================================================================
@ -2271,12 +2306,22 @@ Changes to Python's build process and to the C API include:
have been updated.
(Contributed by Brett Cannon.)
Another new target, "make profile-opt", compiles a Python binary
using GCC's profile-guided optimization. It compiles Python with
profiling enabled, runs the test suite to obtain a set of profiling
results, and then compiles using these results for optimization.
(Contributed by Gregory P. Smith.)
.. ======================================================================
Port-Specific Changes: Windows
-----------------------------------
* The support for Windows 95, 98, ME and NT4 has been dropped.
Python 2.6 requires at least Windows 2000 SP4.
* The :mod:`msvcrt` module now supports
both the normal and wide char variants of the console I/O
API. The :func:`getwch` function reads a keypress and returns a Unicode

View File

@ -5,7 +5,6 @@ default, these calendars have Monday as the first day of the week, and
Sunday as the last (the European convention). Use setfirstweekday() to
set the first day of the week (0=Monday, 6=Sunday)."""
from __future__ import with_statement
import sys
import datetime
import locale as _locale

View File

@ -1,6 +1,7 @@
"""Utilities for with-statement contexts. See PEP 343."""
import sys
from functools import wraps
__all__ = ["contextmanager", "nested", "closing"]
@ -77,14 +78,9 @@ def contextmanager(func):
<cleanup>
"""
@wraps(func)
def helper(*args, **kwds):
return GeneratorContextManager(func(*args, **kwds))
try:
helper.__name__ = func.__name__
helper.__doc__ = func.__doc__
helper.__dict__ = func.__dict__
except:
pass
return helper

View File

@ -0,0 +1,81 @@
from ctypes import *
import array
import gc
import unittest
class X(Structure):
_fields_ = [("c_int", c_int)]
init_called = False
def __init__(self):
self._init_called = True
class Test(unittest.TestCase):
def test_fom_buffer(self):
a = array.array("i", range(16))
x = (c_int * 16).from_buffer(a)
y = X.from_buffer(a)
self.assertEqual(y.c_int, a[0])
self.failIf(y.init_called)
self.assertEqual(x[:], a.tolist())
a[0], a[-1] = 200, -200
self.assertEqual(x[:], a.tolist())
self.assert_(a in x._objects.values())
self.assertRaises(ValueError,
c_int.from_buffer, a, -1)
expected = x[:]
del a; gc.collect(); gc.collect(); gc.collect()
self.assertEqual(x[:], expected)
self.assertRaises(TypeError,
(c_char * 16).from_buffer, "a" * 16)
def test_fom_buffer_with_offset(self):
a = array.array("i", range(16))
x = (c_int * 15).from_buffer(a, sizeof(c_int))
self.assertEqual(x[:], a.tolist()[1:])
self.assertRaises(ValueError, lambda: (c_int * 16).from_buffer(a, sizeof(c_int)))
self.assertRaises(ValueError, lambda: (c_int * 1).from_buffer(a, 16 * sizeof(c_int)))
def BROKEN_test_from_buffer_copy(self):
a = array.array("i", range(16))
x = (c_int * 16).from_buffer_copy(a)
y = X.from_buffer_copy(a)
self.assertEqual(y.c_int, a[0])
self.failIf(y.init_called)
self.assertEqual(x[:], list(range(16)))
a[0], a[-1] = 200, -200
self.assertEqual(x[:], list(range(16)))
self.assertEqual(x._objects, None)
self.assertRaises(ValueError,
c_int.from_buffer, a, -1)
del a; gc.collect(); gc.collect(); gc.collect()
self.assertEqual(x[:], list(range(16)))
x = (c_char * 16).from_buffer_copy("a" * 16)
self.assertEqual(x[:], "a" * 16)
def test_fom_buffer_copy_with_offset(self):
a = array.array("i", range(16))
x = (c_int * 15).from_buffer_copy(a, sizeof(c_int))
self.assertEqual(x[:], a.tolist()[1:])
self.assertRaises(ValueError,
(c_int * 16).from_buffer_copy, a, sizeof(c_int))
self.assertRaises(ValueError,
(c_int * 1).from_buffer_copy, a, 16 * sizeof(c_int))
if __name__ == '__main__':
unittest.main()

View File

@ -478,11 +478,7 @@ def localcontext(ctx=None):
# General Decimal Arithmetic Specification
return +s # Convert result to normal context
"""
# The string below can't be included in the docstring until Python 2.6
# as the doctest module doesn't understand __future__ statements
"""
>>> from __future__ import with_statement
>>> setcontext(DefaultContext)
>>> print(getcontext().prec)
28
>>> with localcontext():
@ -3618,9 +3614,9 @@ class Context(object):
if _ignored_flags is None:
_ignored_flags = []
if not isinstance(flags, dict):
flags = dict([(s,s in flags) for s in _signals])
flags = dict([(s, int(s in flags)) for s in _signals])
if traps is not None and not isinstance(traps, dict):
traps = dict([(s,s in traps) for s in _signals])
traps = dict([(s, int(s in traps)) for s in _signals])
for name, val in locals().items():
if val is None:
setattr(self, name, _copy.copy(getattr(DefaultContext, name)))

View File

@ -48,6 +48,10 @@ class bdist_wininst(Command):
"Fully qualified filename of a script to be run before "
"any files are installed. This script need not be in the "
"distribution"),
('user-access-control=', None,
"specify Vista's UAC handling - 'none'/default=no "
"handling, 'auto'=use UAC if target Python installed for "
"all users, 'force'=always use UAC"),
]
boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize',
@ -66,6 +70,7 @@ class bdist_wininst(Command):
self.skip_build = 0
self.install_script = None
self.pre_install_script = None
self.user_access_control = None
def finalize_options(self):
@ -211,6 +216,8 @@ class bdist_wininst(Command):
lines.append("target_optimize=%d" % (not self.no_target_optimize))
if self.target_version:
lines.append("target_version=%s" % self.target_version)
if self.user_access_control:
lines.append("user_access_control=%s" % self.user_access_control)
title = self.title or self.distribution.get_fullname()
lines.append("title=%s" % escape(title))

View File

@ -594,14 +594,25 @@ class MSVCCompiler(CCompiler) :
# needed! Make sure they are generated in the temporary build
# directory. Since they have different names for debug and release
# builds, they can go into the same directory.
build_temp = os.path.dirname(objects[0])
if export_symbols is not None:
(dll_name, dll_ext) = os.path.splitext(
os.path.basename(output_filename))
implib_file = os.path.join(
os.path.dirname(objects[0]),
build_temp,
self.library_filename(dll_name))
ld_args.append ('/IMPLIB:' + implib_file)
# Embedded manifests are recommended - see MSDN article titled
# "How to: Embed a Manifest Inside a C/C++ Application"
# (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
# Ask the linker to generate the manifest in the temp dir, so
# we can embed it later.
temp_manifest = os.path.join(
build_temp,
os.path.basename(output_filename) + ".manifest")
ld_args.append('/MANIFESTFILE:' + temp_manifest)
if extra_preargs:
ld_args[:0] = extra_preargs
if extra_postargs:
@ -613,6 +624,18 @@ class MSVCCompiler(CCompiler) :
except DistutilsExecError as msg:
raise LinkError(msg)
# embed the manifest
# XXX - this is somewhat fragile - if mt.exe fails, distutils
# will still consider the DLL up-to-date, but it will not have a
# manifest. Maybe we should link to a temp file? OTOH, that
# implies a build environment error that shouldn't go undetected.
mfid = 1 if target_desc == CCompiler.EXECUTABLE else 2
out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
try:
self.spawn(['mt.exe', '-nologo', '-manifest',
temp_manifest, out_arg])
except DistutilsExecError as msg:
raise LinkError(msg)
else:
log.debug("skipping %s (up-to-date)", output_filename)

View File

@ -1,7 +1,10 @@
"""Utilities to get a password and/or the current user name.
getpass(prompt) - prompt for a password, with echo turned off
getuser() - get the user name from the environment or password database
getpass(prompt[, stream]) - Prompt for a password, with echo turned off.
getuser() - Get the user name from the environment or password database.
GetPassWarning - This UserWarning is issued when getpass() cannot prevent
echoing of the password contents while reading.
On Windows, the msvcrt module will be used.
On the Mac EasyDialogs.AskPassword is used, if available.
@ -10,34 +13,70 @@ On the Mac EasyDialogs.AskPassword is used, if available.
# Authors: Piers Lauder (original)
# Guido van Rossum (Windows support and cleanup)
# Gregory P. Smith (tty support & GetPassWarning)
import sys
import os, sys, warnings
__all__ = ["getpass","getuser","GetPassWarning"]
class GetPassWarning(UserWarning): pass
__all__ = ["getpass","getuser"]
def unix_getpass(prompt='Password: ', stream=None):
"""Prompt for a password, with echo turned off.
The prompt is written on stream, by default stdout.
Restore terminal settings at end.
Args:
prompt: Written on stream to ask for the input. Default: 'Password: '
stream: A writable file object to display the prompt. Defaults to
the tty. If no tty is available defaults to sys.stderr.
Returns:
The seKr3t input.
Raises:
EOFError: If our input tty or stdin was closed.
GetPassWarning: When we were unable to turn echo off on the input.
Always restores terminal settings before returning.
"""
if stream is None:
stream = sys.stdout
fd = None
tty = None
try:
fd = sys.stdin.fileno()
except:
return default_getpass(prompt)
# Always try reading and writing directly on the tty first.
fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
tty = os.fdopen(fd, 'w+', 1)
input = tty
if not stream:
stream = tty
except EnvironmentError as e:
# If that fails, see if stdin can be controlled.
try:
fd = sys.stdin.fileno()
except:
passwd = fallback_getpass(prompt, stream)
input = sys.stdin
if not stream:
stream = sys.stderr
old = termios.tcgetattr(fd) # a copy to save
new = old[:]
new[3] = new[3] & ~termios.ECHO # 3 == 'lflags'
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
passwd = _raw_input(prompt, stream)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
if fd is not None:
passwd = None
try:
old = termios.tcgetattr(fd) # a copy to save
new = old[:]
new[3] &= ~termios.ECHO # 3 == 'lflags'
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
passwd = _raw_input(prompt, stream, input=input)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
except termios.error as e:
if passwd is not None:
# _raw_input succeeded. The final tcsetattr failed. Reraise
# instead of leaving the terminal in an unknown state.
raise
# We can't control the tty or stdin. Give up and use normal IO.
# fallback_getpass() raises an appropriate warning.
del input, tty # clean up unused file objects before blocking
passwd = fallback_getpass(prompt, stream)
stream.write('\n')
return passwd
@ -46,7 +85,7 @@ def unix_getpass(prompt='Password: ', stream=None):
def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
if sys.stdin is not sys.__stdin__:
return default_getpass(prompt, stream)
return fallback_getpass(prompt, stream)
import msvcrt
for c in prompt:
msvcrt.putwch(c)
@ -66,20 +105,26 @@ def win_getpass(prompt='Password: ', stream=None):
return pw
def default_getpass(prompt='Password: ', stream=None):
print("Warning: Problem with getpass. Passwords may be echoed.", file=sys.stderr)
def fallback_getpass(prompt='Password: ', stream=None):
warnings.warn("Can not control echo on the terminal.", GetPassWarning,
stacklevel=2)
if not stream:
stream = sys.stderr
print("Warning: Password input may be echoed.", file=stream)
return _raw_input(prompt, stream)
def _raw_input(prompt="", stream=None):
def _raw_input(prompt="", stream=None, input=None):
# This doesn't save the string in the GNU readline history.
if stream is None:
stream = sys.stdout
if not stream:
stream = sys.stderr
if not input:
input = sys.stdin
prompt = str(prompt)
if prompt:
stream.write(prompt)
stream.flush()
line = sys.stdin.readline()
line = input.readline()
if not line:
raise EOFError
if line[-1] == '\n':
@ -119,7 +164,7 @@ except (ImportError, AttributeError):
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass
getpass = fallback_getpass
else:
getpass = AskPassword
else:

View File

@ -23,6 +23,10 @@ from idlelib.HyperParser import HyperParser
import __main__
SEPS = os.sep
if os.altsep: # e.g. '/' on Windows...
SEPS += os.altsep
class AutoComplete:
menudefs = [
@ -70,7 +74,7 @@ class AutoComplete:
if lastchar == ".":
self._open_completions_later(False, False, False,
COMPLETE_ATTRIBUTES)
elif lastchar == os.sep:
elif lastchar in SEPS:
self._open_completions_later(False, False, False,
COMPLETE_FILES)
@ -126,7 +130,7 @@ class AutoComplete:
i -= 1
comp_start = curline[i:j]
j = i
while i and curline[i-1] in FILENAME_CHARS+os.sep:
while i and curline[i-1] in FILENAME_CHARS + SEPS:
i -= 1
comp_what = curline[i:j]
elif hp.is_in_code() and (not mode or mode==COMPLETE_ATTRIBUTES):

View File

@ -54,9 +54,9 @@ class AutoCompleteWindow:
self.lastkey_was_tab = False
def _change_start(self, newstart):
min_len = min(len(self.start), len(newstart))
i = 0
while i < len(self.start) and i < len(newstart) and \
self.start[i] == newstart[i]:
while i < min_len and self.start[i] == newstart[i]:
i += 1
if i < len(self.start):
self.widget.delete("%s+%dc" % (self.startindex, i),
@ -98,13 +98,17 @@ class AutoCompleteWindow:
i = m + 1
last = i-1
if first == last: # only one possible completion
return self.completions[first]
# We should return the maximum prefix of first and last
first_comp = self.completions[first]
last_comp = self.completions[last]
min_len = min(len(first_comp), len(last_comp))
i = len(s)
while len(self.completions[first]) > i and \
len(self.completions[last]) > i and \
self.completions[first][i] == self.completions[last][i]:
while i < min_len and first_comp[i] == last_comp[i]:
i += 1
return self.completions[first][:i]
return first_comp[:i]
def _selection_changed(self):
"""Should be called when the selection of the Listbox has changed.
@ -118,8 +122,9 @@ class AutoCompleteWindow:
if self._binary_search(lts) == cursel:
newstart = lts
else:
min_len = min(len(lts), len(selstart))
i = 0
while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]:
while i < min_len and lts[i] == selstart[i]:
i += 1
newstart = selstart[:i]
self._change_start(newstart)

View File

@ -155,6 +155,7 @@ class EditorWindow(object):
text.bind("<Right>", self.move_at_edge_if_selection(1))
text.bind("<<del-word-left>>", self.del_word_left)
text.bind("<<del-word-right>>", self.del_word_right)
text.bind("<<beginning-of-line>>", self.home_callback)
if flist:
flist.inversedict[self] = key
@ -277,6 +278,50 @@ class EditorWindow(object):
self.flist.new(dirname)
return "break"
def home_callback(self, event):
if (event.state & 12) != 0 and event.keysym == "Home":
# state&1==shift, state&4==control, state&8==alt
return # <Modifier-Home>; fall back to class binding
if self.text.index("iomark") and \
self.text.compare("iomark", "<=", "insert lineend") and \
self.text.compare("insert linestart", "<=", "iomark"):
insertpt = int(self.text.index("iomark").split(".")[1])
else:
line = self.text.get("insert linestart", "insert lineend")
for insertpt in xrange(len(line)):
if line[insertpt] not in (' ','\t'):
break
else:
insertpt=len(line)
lineat = int(self.text.index("insert").split('.')[1])
if insertpt == lineat:
insertpt = 0
dest = "insert linestart+"+str(insertpt)+"c"
if (event.state&1) == 0:
# shift not pressed
self.text.tag_remove("sel", "1.0", "end")
else:
if not self.text.index("sel.first"):
self.text.mark_set("anchor","insert")
first = self.text.index(dest)
last = self.text.index("anchor")
if self.text.compare(first,">",last):
first,last = last,first
self.text.tag_remove("sel", "1.0", "end")
self.text.tag_add("sel", first, last)
self.text.mark_set("insert", dest)
self.text.see("insert")
return "break"
def set_status_bar(self):
self.status_bar = self.MultiStatusBar(self.top)
if macosxSupport.runningAsOSXApp():

View File

@ -806,7 +806,6 @@ class PyShell(OutputWindow):
text.bind("<<newline-and-indent>>", self.enter_callback)
text.bind("<<plain-newline-and-indent>>", self.linefeed_callback)
text.bind("<<interrupt-execution>>", self.cancel_callback)
text.bind("<<beginning-of-line>>", self.home_callback)
text.bind("<<end-of-file>>", self.eof_callback)
text.bind("<<open-stack-viewer>>", self.open_stack_viewer)
text.bind("<<toggle-debugger>>", self.toggle_debugger)
@ -1048,16 +1047,6 @@ class PyShell(OutputWindow):
self.top.quit()
return "break"
def home_callback(self, event):
if event.state != 0 and event.keysym == "Home":
return # <Modifier-Home>; fall back to class binding
if self.text.compare("iomark", "<=", "insert") and \
self.text.compare("insert linestart", "<=", "iomark"):
self.text.mark_set("insert", "iomark")
self.text.tag_remove("sel", "1.0", "end")
self.text.see("insert")
return "break"
def linefeed_callback(self, event):
# Insert a linefeed without entering anything (still autoindented)
if self.reading:

View File

@ -204,7 +204,10 @@ class IdleConf:
if not os.path.exists(userDir):
warn = ('\n Warning: os.path.expanduser("~") points to\n '+
userDir+',\n but the path does not exist.\n')
sys.stderr.write(warn)
try:
sys.stderr.write(warn)
except IOError:
pass
userDir = '~'
if userDir == "~": # still no path to home!
# traditionally IDLE has defaulted to os.getcwd(), is this adequate?
@ -247,7 +250,10 @@ class IdleConf:
' from section %r.\n'
' returning default value: %r\n' %
(option, section, default))
sys.stderr.write(warning)
try:
sys.stderr.write(warning)
except IOError:
pass
return default
def SetOption(self, configType, section, option, value):
@ -356,7 +362,10 @@ class IdleConf:
'\n from theme %r.\n'
' returning default value: %r\n' %
(element, themeName, theme[element]))
sys.stderr.write(warning)
try:
sys.stderr.write(warning)
except IOError:
pass
colour=cfgParser.Get(themeName,element,default=theme[element])
theme[element]=colour
return theme
@ -610,7 +619,10 @@ class IdleConf:
'\n from key set %r.\n'
' returning default value: %r\n' %
(event, keySetName, keyBindings[event]))
sys.stderr.write(warning)
try:
sys.stderr.write(warning)
except IOError:
pass
return keyBindings
def GetExtraHelpSourceList(self,configSet):

View File

@ -18,6 +18,8 @@ import sys
import difflib
import optparse
import logging
from collections import defaultdict
from itertools import chain
# Local imports
from .pgen2 import driver
@ -96,6 +98,43 @@ def get_all_fix_names():
fix_names.sort()
return fix_names
def get_head_types(pat):
""" Accepts a pytree Pattern Node and returns a set
of the pattern types which will match first. """
if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
# NodePatters must either have no type and no content
# or a type and content -- so they don't get any farther
# Always return leafs
return set([pat.type])
if isinstance(pat, pytree.NegatedPattern):
if pat.content:
return get_head_types(pat.content)
return set([None]) # Negated Patterns don't have a type
if isinstance(pat, pytree.WildcardPattern):
# Recurse on each node in content
r = set()
for p in pat.content:
for x in p:
r.update(get_head_types(x))
return r
raise Exception("Oh no! I don't understand pattern %s" %(pat))
def get_headnode_dict(fixer_list):
""" Accepts a list of fixers and returns a dictionary
of head node type --> fixer list. """
head_nodes = defaultdict(list)
for fixer in fixer_list:
if not fixer.pattern:
head_nodes[None].append(fixer)
continue
for t in get_head_types(fixer.pattern):
head_nodes[t].append(fixer)
return head_nodes
class RefactoringTool(object):
@ -114,6 +153,10 @@ class RefactoringTool(object):
convert=pytree.convert,
logger=self.logger)
self.pre_order, self.post_order = self.get_fixers()
self.pre_order = get_headnode_dict(self.pre_order)
self.post_order = get_headnode_dict(self.post_order)
self.files = [] # List of files that were or should be modified
def get_fixers(self):
@ -286,7 +329,11 @@ class RefactoringTool(object):
Returns:
True if the tree was modified, False otherwise.
"""
all_fixers = self.pre_order + self.post_order
# Two calls to chain are required because pre_order.values()
# will be a list of lists of fixers:
# [[<fixer ...>, <fixer ...>], [<fixer ...>]]
all_fixers = chain(chain(*self.pre_order.values()),\
chain(*self.post_order.values()))
for fixer in all_fixers:
fixer.start_tree(tree, name)
@ -312,7 +359,7 @@ class RefactoringTool(object):
if not fixers:
return
for node in traversal:
for fixer in fixers:
for fixer in fixers[node.type] + fixers[None]:
results = fixer.match(node)
if results:
new = fixer.transform(node, results)

View File

@ -33,8 +33,10 @@ class FixerTestCase(support.TestCase):
self.fixer_log = []
self.filename = "<string>"
for order in (self.refactor.pre_order, self.refactor.post_order):
for fixer in order:
from itertools import chain
for order in (self.refactor.pre_order.values(),\
self.refactor.post_order.values()):
for fixer in chain(*order):
fixer.log = self.fixer_log
def _check(self, before, after):

View File

@ -1,6 +1,7 @@
# Generated from 'AEDataModel.h'
def FOUR_CHAR_CODE(x): return x.encode("latin-1")
typeApplicationBundleID = FOUR_CHAR_CODE('bund')
typeBoolean = FOUR_CHAR_CODE('bool')
typeChar = FOUR_CHAR_CODE('TEXT')
typeSInt16 = FOUR_CHAR_CODE('shor')

View File

@ -1,3 +1,4 @@
# -coding=latin1-
svTempDisable = -32768 #svTempDisable
svDisabled = -32640 #Reserve range -32640 to -32768 for Apple temp disables.
fontNotOutlineErr = -32615 #bitmap font passed to routine that does outlines only

View File

@ -27,7 +27,7 @@ SEND_MODE = kAENoReply # kAEWaitReply hangs when run from Terminal.app itself
def run(command):
"""Run a shell command in a new Terminal.app window."""
termAddress = AE.AECreateDesc(typeApplSignature, TERMINAL_SIG)
termAddress = AE.AECreateDesc(typeApplicationBundleID, "com.apple.Terminal")
theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress,
kAutoGenerateReturnID, kAnyTransactionID)
commandDesc = AE.AECreateDesc(typeChar, command)

View File

@ -41,8 +41,8 @@ Instances of this class have the following instance variables:
import sys
import imp
import tokenize # Python tokenizer
from token import NAME, DEDENT, NEWLINE, OP
import tokenize
from token import NAME, DEDENT, OP
from operator import itemgetter
__all__ = ["readmodule", "readmodule_ex", "Class", "Function"]
@ -73,37 +73,37 @@ class Function:
self.file = file
self.lineno = lineno
def readmodule(module, path=[]):
def readmodule(module, path=None):
'''Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary.'''
dict = _readmodule(module, path)
res = {}
for key, value in dict.items():
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
return res
def readmodule_ex(module, path=[]):
def readmodule_ex(module, path=None):
'''Read a module file and return a dictionary of classes.
Search for MODULE in PATH and sys.path, read and parse the
module and return a dictionary with one entry for each class
found in the module.
'''
return _readmodule(module, path or [])
If INPACKAGE is true, it must be the dotted name of the package in
def _readmodule(module, path, inpackage=None):
'''Do the hard work for readmodule[_ex].
If INPACKAGE is given, it must be the dotted name of the package in
which we are searching for a submodule, and then PATH must be the
package search path; otherwise, we are searching for a top-level
module, and PATH is combined with sys.path.
'''
return _readmodule(module, path)
def _readmodule(module, path, inpackage=None):
'''Do the hard work for readmodule[_ex].'''
# Compute the full module name (prepending inpackage if set)
if inpackage:
if inpackage is not None:
fullmodule = "%s.%s" % (inpackage, module)
else:
fullmodule = module
@ -116,7 +116,7 @@ def _readmodule(module, path, inpackage=None):
dict = {}
# Check if it is a built-in module; we don't do much for these
if module in sys.builtin_module_names and not inpackage:
if module in sys.builtin_module_names and inpackage is None:
_modules[module] = dict
return dict
@ -126,22 +126,22 @@ def _readmodule(module, path, inpackage=None):
package = module[:i]
submodule = module[i+1:]
parent = _readmodule(package, path, inpackage)
if inpackage:
if inpackage is not None:
package = "%s.%s" % (inpackage, package)
return _readmodule(submodule, parent['__path__'], package)
# Search the path for the module
f = None
if inpackage:
f, file, (suff, mode, type) = imp.find_module(module, path)
if inpackage is not None:
f, fname, (_s, _m, ty) = imp.find_module(module, path)
else:
f, file, (suff, mode, type) = imp.find_module(module, path + sys.path)
if type == imp.PKG_DIRECTORY:
dict['__path__'] = [file]
path = [file] + path
f, file, (suff, mode, type) = imp.find_module('__init__', [file])
f, fname, (_s, _m, ty) = imp.find_module(module, path + sys.path)
if ty == imp.PKG_DIRECTORY:
dict['__path__'] = [fname]
path = [fname] + path
f, fname, (_s, _m, ty) = imp.find_module('__init__', [fname])
_modules[fullmodule] = dict
if type != imp.PY_SOURCE:
if ty != imp.PY_SOURCE:
# not Python source, can't do anything with this module
f.close()
return dict
@ -150,7 +150,7 @@ def _readmodule(module, path, inpackage=None):
g = tokenize.generate_tokens(f.readline)
try:
for tokentype, token, start, end, line in g:
for tokentype, token, start, _end, _line in g:
if tokentype == DEDENT:
lineno, thisindent = start
# close nested classes and defs
@ -161,7 +161,7 @@ def _readmodule(module, path, inpackage=None):
# close previous nested classes and defs
while stack and stack[-1][1] >= thisindent:
del stack[-1]
tokentype, meth_name, start, end, line = next(g)
tokentype, meth_name, start = next(g)[0:3]
if tokentype != NAME:
continue # Syntax error
if stack:
@ -172,18 +172,19 @@ def _readmodule(module, path, inpackage=None):
# else it's a nested def
else:
# it's a function
dict[meth_name] = Function(fullmodule, meth_name, file, lineno)
dict[meth_name] = Function(fullmodule, meth_name,
fname, lineno)
stack.append((None, thisindent)) # Marker for nested fns
elif token == 'class':
lineno, thisindent = start
# close previous nested classes and defs
while stack and stack[-1][1] >= thisindent:
del stack[-1]
tokentype, class_name, start, end, line = next(g)
tokentype, class_name, start = next(g)[0:3]
if tokentype != NAME:
continue # Syntax error
# parse what follows the class name
tokentype, token, start, end, line = next(g)
tokentype, token, start = next(g)[0:3]
inherit = None
if token == '(':
names = [] # List of superclasses
@ -191,7 +192,7 @@ def _readmodule(module, path, inpackage=None):
level = 1
super = [] # Tokens making up current superclass
while True:
tokentype, token, start, end, line = next(g)
tokentype, token, start = next(g)[0:3]
if token in (')', ',') and level == 1:
n = "".join(super)
if n in dict:
@ -224,16 +225,17 @@ def _readmodule(module, path, inpackage=None):
super.append(token)
# expressions in the base list are not supported
inherit = names
cur_class = Class(fullmodule, class_name, inherit, file, lineno)
cur_class = Class(fullmodule, class_name, inherit,
fname, lineno)
if not stack:
dict[class_name] = cur_class
stack.append((cur_class, thisindent))
elif token == 'import' and start[1] == 0:
modules = _getnamelist(g)
for mod, mod2 in modules:
for mod, _mod2 in modules:
try:
# Recursively read the imported module
if not inpackage:
if inpackage is None:
_readmodule(mod, path)
else:
try:
@ -287,7 +289,7 @@ def _getnamelist(g):
name2 = None
names.append((name, name2))
while token != "," and "\n" not in token:
tokentype, token, start, end, line = next(g)
token = next(g)[1]
if token != ",":
break
return names
@ -297,15 +299,15 @@ def _getname(g):
# name is the dotted name, or None if there was no dotted name,
# and token is the next input token.
parts = []
tokentype, token, start, end, line = next(g)
tokentype, token = next(g)[0:2]
if tokentype != NAME and token != '*':
return (None, token)
parts.append(token)
while True:
tokentype, token, start, end, line = next(g)
tokentype, token = next(g)[0:2]
if token != '.':
break
tokentype, token, start, end, line = next(g)
tokentype, token = next(g)[0:2]
if tokentype != NAME:
break
parts.append(token)

View File

@ -9,16 +9,11 @@
The robots.txt Exclusion Protocol is implemented as specified in
http://info.webcrawler.com/mak/projects/robots/norobots-rfc.html
"""
import urlparse,urllib
import urlparse
import urllib
__all__ = ["RobotFileParser"]
debug = 0
def _debug(msg):
if debug: print(msg)
class RobotFileParser:
""" This class provides a set of methods to read, parse and answer
questions about a single robots.txt file.
@ -67,12 +62,9 @@ class RobotFileParser:
self.errcode = opener.errcode
if self.errcode in (401, 403):
self.disallow_all = True
_debug("disallow all")
elif self.errcode >= 400:
self.allow_all = True
_debug("allow all")
elif self.errcode == 200 and lines:
_debug("parse lines")
self.parse(lines)
def _add_entry(self, entry):
@ -93,19 +85,16 @@ class RobotFileParser:
for line in lines:
linenumber = linenumber + 1
if not line:
if state==1:
_debug("line %d: warning: you should insert"
" allow: or disallow: directives below any"
" user-agent: line" % linenumber)
if state == 1:
entry = Entry()
state = 0
elif state==2:
elif state == 2:
self._add_entry(entry)
entry = Entry()
state = 0
# remove optional comment and strip line
i = line.find('#')
if i>=0:
if i >= 0:
line = line[:i]
line = line.strip()
if not line:
@ -115,41 +104,24 @@ class RobotFileParser:
line[0] = line[0].strip().lower()
line[1] = urllib.unquote(line[1].strip())
if line[0] == "user-agent":
if state==2:
_debug("line %d: warning: you should insert a blank"
" line before any user-agent"
" directive" % linenumber)
if state == 2:
self._add_entry(entry)
entry = Entry()
entry.useragents.append(line[1])
state = 1
elif line[0] == "disallow":
if state==0:
_debug("line %d: error: you must insert a user-agent:"
" directive before this line" % linenumber)
else:
if state != 0:
entry.rulelines.append(RuleLine(line[1], False))
state = 2
elif line[0] == "allow":
if state==0:
_debug("line %d: error: you must insert a user-agent:"
" directive before this line" % linenumber)
else:
if state != 0:
entry.rulelines.append(RuleLine(line[1], True))
else:
_debug("line %d: warning: unknown key %s" % (linenumber,
line[0]))
else:
_debug("line %d: error: malformed line %s"%(linenumber, line))
if state==2:
if state == 2:
self.entries.append(entry)
_debug("Parsed rules:\n%s" % str(self))
def can_fetch(self, useragent, url):
"""using the parsed robots.txt decide if useragent can fetch url"""
_debug("Checking robots.txt allowance for:\n user agent: %s\n url: %s" %
(useragent, url))
if self.disallow_all:
return False
if self.allow_all:
@ -182,10 +154,10 @@ class RuleLine:
self.allowance = allowance
def applies_to(self, filename):
return self.path=="*" or filename.startswith(self.path)
return self.path == "*" or filename.startswith(self.path)
def __str__(self):
return (self.allowance and "Allow" or "Disallow")+": "+self.path
return (self.allowance and "Allow" or "Disallow") + ": " + self.path
class Entry:
@ -207,7 +179,7 @@ class Entry:
# split the name token and make it lower case
useragent = useragent.split("/")[0].lower()
for agent in self.useragents:
if agent=='*':
if agent == '*':
# we have the catch-all agent
return True
agent = agent.lower()
@ -220,7 +192,6 @@ class Entry:
- our agent applies to this entry
- filename is URL decoded"""
for line in self.rulelines:
_debug((filename, str(line), line.allowance))
if line.applies_to(filename):
return line.allowance
return True
@ -239,56 +210,3 @@ class URLopener(urllib.FancyURLopener):
self.errcode = errcode
return urllib.FancyURLopener.http_error_default(self, url, fp, errcode,
errmsg, headers)
def _check(a,b):
if not b:
ac = "access denied"
else:
ac = "access allowed"
if a!=b:
print("failed")
else:
print("ok (%s)" % ac)
print()
def _test():
global debug
rp = RobotFileParser()
debug = 1
# robots.txt that exists, gotten to by redirection
rp.set_url('http://www.musi-cal.com/robots.txt')
rp.read()
# test for re.escape
_check(rp.can_fetch('*', 'http://www.musi-cal.com/'), 1)
# this should match the first rule, which is a disallow
_check(rp.can_fetch('', 'http://www.musi-cal.com/'), 0)
# various cherry pickers
_check(rp.can_fetch('CherryPickerSE',
'http://www.musi-cal.com/cgi-bin/event-search'
'?city=San+Francisco'), 0)
_check(rp.can_fetch('CherryPickerSE/1.0',
'http://www.musi-cal.com/cgi-bin/event-search'
'?city=San+Francisco'), 0)
_check(rp.can_fetch('CherryPickerSE/1.5',
'http://www.musi-cal.com/cgi-bin/event-search'
'?city=San+Francisco'), 0)
# case sensitivity
_check(rp.can_fetch('ExtractorPro', 'http://www.musi-cal.com/blubba'), 0)
_check(rp.can_fetch('extractorpro', 'http://www.musi-cal.com/blubba'), 0)
# substring test
_check(rp.can_fetch('toolpak/1.1', 'http://www.musi-cal.com/blubba'), 0)
# tests for catch-all * agent
_check(rp.can_fetch('spam', 'http://www.musi-cal.com/search'), 0)
_check(rp.can_fetch('spam', 'http://www.musi-cal.com/Musician/me'), 1)
_check(rp.can_fetch('spam', 'http://www.musi-cal.com/'), 1)
_check(rp.can_fetch('spam', 'http://www.musi-cal.com/'), 1)
# robots.txt that does not exist
rp.set_url('http://www.lycos.com/robots.txt')
rp.read()
_check(rp.can_fetch('Mozilla', 'http://www.lycos.com/search'), 1)
if __name__ == '__main__':
_test()

View File

@ -131,6 +131,26 @@ class RowFactoryTests(unittest.TestCase):
self.failUnlessEqual(d["a"], row["a"])
self.failUnlessEqual(d["b"], row["b"])
def CheckSqliteRowHashCmp(self):
"""Checks if the row object compares and hashes correctly"""
self.con.row_factory = sqlite.Row
row_1 = self.con.execute("select 1 as a, 2 as b").fetchone()
row_2 = self.con.execute("select 1 as a, 2 as b").fetchone()
row_3 = self.con.execute("select 1 as a, 3 as b").fetchone()
self.failUnless(row_1 == row_1)
self.failUnless(row_1 == row_2)
self.failUnless(row_2 != row_3)
self.failIf(row_1 != row_1)
self.failIf(row_1 != row_2)
self.failIf(row_2 == row_3)
self.failUnlessEqual(row_1, row_2)
self.failUnlessEqual(hash(row_1), hash(row_2))
self.failIfEqual(row_1, row_3)
self.failIfEqual(hash(row_1), hash(row_3))
def tearDown(self):
self.con.close()

View File

@ -109,7 +109,7 @@ class DeclTypesTests(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES)
self.cur = self.con.cursor()
self.cur.execute("create table test(i int, s str, f float, b bool, u unicode, foo foo, bin blob)")
self.cur.execute("create table test(i int, s str, f float, b bool, u unicode, foo foo, bin blob, n1 number, n2 number(5))")
# override float, make them always return the same number
sqlite.converters["FLOAT"] = lambda x: 47.2
@ -118,11 +118,13 @@ class DeclTypesTests(unittest.TestCase):
sqlite.converters["BOOL"] = lambda x: bool(int(x))
sqlite.converters["FOO"] = DeclTypesTests.Foo
sqlite.converters["WRONG"] = lambda x: "WRONG"
sqlite.converters["NUMBER"] = float
def tearDown(self):
del sqlite.converters["FLOAT"]
del sqlite.converters["BOOL"]
del sqlite.converters["FOO"]
del sqlite.converters["NUMBER"]
self.cur.close()
self.con.close()
@ -215,6 +217,19 @@ class DeclTypesTests(unittest.TestCase):
row = self.cur.fetchone()
self.failUnlessEqual(row[0], sample)
def CheckNumber1(self):
self.cur.execute("insert into test(n1) values (5)")
value = self.cur.execute("select n1 from test").fetchone()[0]
# if the converter is not used, it's an int instead of a float
self.failUnlessEqual(type(value), float)
def CheckNumber2(self):
"""Checks wether converter names are cut off at '(' characters"""
self.cur.execute("insert into test(n2) values (5)")
value = self.cur.execute("select n2 from test").fetchone()[0]
# if the converter is not used, it's an int instead of a float
self.failUnlessEqual(type(value), float)
class ColNamesTests(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)

View File

@ -78,8 +78,6 @@ else:
template = "tmp"
tempdir = None
# Internal routines.
_once_lock = _allocate_lock()
@ -252,7 +250,7 @@ def gettempprefix():
tempdir = None
def gettempdir():
"""Accessor for tempdir.tempdir."""
"""Accessor for tempfile.tempdir."""
global tempdir
if tempdir is None:
_once_lock.acquire()
@ -264,8 +262,7 @@ def gettempdir():
return tempdir
def mkstemp(suffix="", prefix=template, dir=None, text=False):
"""mkstemp([suffix, [prefix, [dir, [text]]]])
User-callable function to create and return a unique temporary
"""User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.
@ -302,8 +299,7 @@ def mkstemp(suffix="", prefix=template, dir=None, text=False):
def mkdtemp(suffix="", prefix=template, dir=None):
"""mkdtemp([suffix, [prefix, [dir]]])
User-callable function to create and return a unique temporary
"""User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
@ -334,8 +330,7 @@ def mkdtemp(suffix="", prefix=template, dir=None):
raise IOError(_errno.EEXIST, "No usable temporary directory name found")
def mktemp(suffix="", prefix=template, dir=None):
"""mktemp([suffix, [prefix, [dir]]])
User-callable function to return a unique temporary file name. The
"""User-callable function to return a unique temporary file name. The
file is not created.
Arguments are as for mkstemp, except that the 'text' argument is

View File

@ -0,0 +1,31 @@
# The cycle GC collector can be executed when any GC-tracked object is
# allocated, e.g. during a call to PyList_New(), PyDict_New(), ...
# Moreover, it can invoke arbitrary Python code via a weakref callback.
# This means that there are many places in the source where an arbitrary
# mutation could unexpectedly occur.
# The example below shows list_slice() not expecting the call to
# PyList_New to mutate the input list. (Of course there are many
# more examples like this one.)
import weakref
class A(object):
pass
def callback(x):
del lst[:]
keepalive = []
for i in range(100):
lst = [str(i)]
a = A()
a.cycle = a
keepalive.append(weakref.ref(a, callback))
del a
while lst:
keepalive.append(lst[:])

View File

@ -484,201 +484,6 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
self.assertRaises(TypeError, list, filter(42, (1, 2)))
def test_float(self):
self.assertEqual(float(3.14), 3.14)
self.assertEqual(float(314), 314.0)
self.assertEqual(float(314), 314.0)
self.assertEqual(float(" 3.14 "), 3.14)
self.assertRaises(ValueError, float, " 0x3.1 ")
self.assertRaises(ValueError, float, " -0x3.p-1 ")
self.assertEqual(float(str(b" \u0663.\u0661\u0664 ",'raw-unicode-escape')), 3.14)
self.assertEqual(float("1"*10000), 1e10000) # Inf on both sides
@run_with_locale('LC_NUMERIC', 'fr_FR', 'de_DE')
def test_float_with_comma(self):
# set locale to something that doesn't use '.' for the decimal point
# float must not accept the locale specific decimal point but
# it still has to accept the normal python syntac
import locale
if not locale.localeconv()['decimal_point'] == ',':
return
self.assertEqual(float(" 3.14 "), 3.14)
self.assertEqual(float("+3.14 "), 3.14)
self.assertEqual(float("-3.14 "), -3.14)
self.assertEqual(float(".14 "), .14)
self.assertEqual(float("3. "), 3.0)
self.assertEqual(float("3.e3 "), 3000.0)
self.assertEqual(float("3.2e3 "), 3200.0)
self.assertEqual(float("2.5e-1 "), 0.25)
self.assertEqual(float("5e-1"), 0.5)
self.assertRaises(ValueError, float, " 3,14 ")
self.assertRaises(ValueError, float, " +3,14 ")
self.assertRaises(ValueError, float, " -3,14 ")
self.assertRaises(ValueError, float, " 0x3.1 ")
self.assertRaises(ValueError, float, " -0x3.p-1 ")
self.assertEqual(float(" 25.e-1 "), 2.5)
self.assertEqual(fcmp(float(" .25e-1 "), .025), 0)
def test_floatconversion(self):
# Make sure that calls to __float__() work properly
class Foo0:
def __float__(self):
return 42.
class Foo1(object):
def __float__(self):
return 42.
class Foo2(float):
def __float__(self):
return 42.
class Foo3(float):
def __new__(cls, value=0.):
return float.__new__(cls, 2*value)
def __float__(self):
return self
class Foo4(float):
def __float__(self):
return 42
self.assertAlmostEqual(float(Foo0()), 42.)
self.assertAlmostEqual(float(Foo1()), 42.)
self.assertAlmostEqual(float(Foo2()), 42.)
self.assertAlmostEqual(float(Foo3(21)), 42.)
self.assertRaises(TypeError, float, Foo4(42))
def test_format(self):
# Test the basic machinery of the format() builtin. Don't test
# the specifics of the various formatters
self.assertEqual(format(3, ''), '3')
# Returns some classes to use for various tests. There's
# an old-style version, and a new-style version
def classes_new():
class A(object):
def __init__(self, x):
self.x = x
def __format__(self, format_spec):
return str(self.x) + format_spec
class DerivedFromA(A):
pass
class Simple(object): pass
class DerivedFromSimple(Simple):
def __init__(self, x):
self.x = x
def __format__(self, format_spec):
return str(self.x) + format_spec
class DerivedFromSimple2(DerivedFromSimple): pass
return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
# In 3.0, classes_classic has the same meaning as classes_new
def classes_classic():
class A:
def __init__(self, x):
self.x = x
def __format__(self, format_spec):
return str(self.x) + format_spec
class DerivedFromA(A):
pass
class Simple: pass
class DerivedFromSimple(Simple):
def __init__(self, x):
self.x = x
def __format__(self, format_spec):
return str(self.x) + format_spec
class DerivedFromSimple2(DerivedFromSimple): pass
return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
self.assertEqual(format(A(3), 'spec'), '3spec')
self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
'10abcdef')
class_test(*classes_new())
class_test(*classes_classic())
def empty_format_spec(value):
# test that:
# format(x, '') == str(x)
# format(x) == str(x)
self.assertEqual(format(value, ""), str(value))
self.assertEqual(format(value), str(value))
# for builtin types, format(x, "") == str(x)
empty_format_spec(17**13)
empty_format_spec(1.0)
empty_format_spec(3.1415e104)
empty_format_spec(-3.1415e104)
empty_format_spec(3.1415e-104)
empty_format_spec(-3.1415e-104)
empty_format_spec(object)
empty_format_spec(None)
# TypeError because self.__format__ returns the wrong type
class BadFormatResult:
def __format__(self, format_spec):
return 1.0
self.assertRaises(TypeError, format, BadFormatResult(), "")
# TypeError because format_spec is not unicode or str
self.assertRaises(TypeError, format, object(), 4)
self.assertRaises(TypeError, format, object(), object())
# tests for object.__format__ really belong elsewhere, but
# there's no good place to put them
x = object().__format__('')
self.assert_(x.startswith('<object object at'))
# first argument to object.__format__ must be string
self.assertRaises(TypeError, object().__format__, 3)
self.assertRaises(TypeError, object().__format__, object())
self.assertRaises(TypeError, object().__format__, None)
# make sure we can take a subclass of str as a format spec
class DerivedFromStr(str): pass
self.assertEqual(format(0, DerivedFromStr('10')), ' 0')
def test_floatasratio(self):
for f, ratio in [
(0.875, (7, 8)),
(-0.875, (-7, 8)),
(0.0, (0, 1)),
(11.5, (23, 2)),
]:
self.assertEqual(f.as_integer_ratio(), ratio)
for i in range(10000):
f = random.random()
f *= 10 ** random.randint(-100, 100)
n, d = f.as_integer_ratio()
self.assertEqual(float(n).__truediv__(d), f)
R = fractions.Fraction
self.assertEqual(R(0, 1),
R(*float(0.0).as_integer_ratio()))
self.assertEqual(R(5, 2),
R(*float(2.5).as_integer_ratio()))
self.assertEqual(R(1, 2),
R(*float(0.5).as_integer_ratio()))
self.assertEqual(R(4728779608739021, 2251799813685248),
R(*float(2.1).as_integer_ratio()))
self.assertEqual(R(-4728779608739021, 2251799813685248),
R(*float(-2.1).as_integer_ratio()))
self.assertEqual(R(-2100, 1),
R(*float(-2100.0).as_integer_ratio()))
self.assertRaises(OverflowError, float('inf').as_integer_ratio)
self.assertRaises(OverflowError, float('-inf').as_integer_ratio)
self.assertRaises(ValueError, float('nan').as_integer_ratio)
def test_getattr(self):
import sys
self.assert_(getattr(sys, 'stdout') is sys.stdout)
@ -737,266 +542,6 @@ class BuiltinTest(unittest.TestCase):
# Test input() later, alphabetized as if it were raw_input
def test_int(self):
self.assertEqual(int(314), 314)
self.assertEqual(int(3.14), 3)
self.assertEqual(int(314), 314)
# Check that conversion from float truncates towards zero
self.assertEqual(int(-3.14), -3)
self.assertEqual(int(3.9), 3)
self.assertEqual(int(-3.9), -3)
self.assertEqual(int(3.5), 3)
self.assertEqual(int(-3.5), -3)
# Different base:
self.assertEqual(int("10",16), 16)
# Test conversion from strings and various anomalies
# Testing with no sign at front
for s, v in test_conv_no_sign:
for prefix in "", " ", "\t", " \t\t ":
ss = prefix + s
vv = v
try:
self.assertEqual(int(ss), vv)
except v:
pass
# No whitespaces allowed between + or - sign and the number
for s, v in test_conv_sign:
for sign in "+", "-":
for prefix in "", " ", "\t", " \t\t ":
ss = prefix + sign + s
vv = v
if sign == "-" and v is not ValueError:
vv = -v
try:
self.assertEqual(int(ss), vv)
except v:
pass
s = repr(-1-sys.maxsize)
x = int(s)
self.assertEqual(x+1, -sys.maxsize)
self.assert_(isinstance(x, int))
# should return long
self.assertEqual(int(s[1:]), sys.maxsize+1)
# should return long
x = int(1e100)
self.assert_(isinstance(x, int))
x = int(-1e100)
self.assert_(isinstance(x, int))
# SF bug 434186: 0x80000000/2 != 0x80000000>>1.
# Worked by accident in Windows release build, but failed in debug build.
# Failed in all Linux builds.
x = -1-sys.maxsize
self.assertEqual(x >> 1, x//2)
self.assertRaises(ValueError, int, '123\0')
self.assertRaises(ValueError, int, '53', 40)
# SF bug 1545497: embedded NULs were not detected with
# explicit base
self.assertRaises(ValueError, int, '123\0', 10)
self.assertRaises(ValueError, int, '123\x00 245', 20)
x = int('1' * 600)
self.assert_(isinstance(x, int))
x = int(chr(0x661) * 600)
self.assert_(isinstance(x, int))
self.assertRaises(TypeError, int, 1, 12)
# tests with base 0
self.assertRaises(ValueError, int, ' 0123 ', 0) # old octal syntax
self.assertEqual(int('000', 0), 0)
self.assertEqual(int('0o123', 0), 83)
self.assertEqual(int('0x123', 0), 291)
self.assertEqual(int('0b100', 0), 4)
self.assertEqual(int(' 0O123 ', 0), 83)
self.assertEqual(int(' 0X123 ', 0), 291)
self.assertEqual(int(' 0B100 ', 0), 4)
# without base still base 10
self.assertEqual(int('0123'), 123)
self.assertEqual(int('0123', 10), 123)
# tests with prefix and base != 0
self.assertEqual(int('0x123', 16), 291)
self.assertEqual(int('0o123', 8), 83)
self.assertEqual(int('0b100', 2), 4)
self.assertEqual(int('0X123', 16), 291)
self.assertEqual(int('0O123', 8), 83)
self.assertEqual(int('0B100', 2), 4)
# Bug 1679: "0x" is not a valid hex literal
self.assertRaises(ValueError, int, "0x", 16)
self.assertRaises(ValueError, int, "0x", 0)
# SF bug 1334662: int(string, base) wrong answers
# Various representations of 2**32 evaluated to 0
# rather than 2**32 in previous versions
self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296)
self.assertEqual(int('102002022201221111211', 3), 4294967296)
self.assertEqual(int('10000000000000000', 4), 4294967296)
self.assertEqual(int('32244002423141', 5), 4294967296)
self.assertEqual(int('1550104015504', 6), 4294967296)
self.assertEqual(int('211301422354', 7), 4294967296)
self.assertEqual(int('40000000000', 8), 4294967296)
self.assertEqual(int('12068657454', 9), 4294967296)
self.assertEqual(int('4294967296', 10), 4294967296)
self.assertEqual(int('1904440554', 11), 4294967296)
self.assertEqual(int('9ba461594', 12), 4294967296)
self.assertEqual(int('535a79889', 13), 4294967296)
self.assertEqual(int('2ca5b7464', 14), 4294967296)
self.assertEqual(int('1a20dcd81', 15), 4294967296)
self.assertEqual(int('100000000', 16), 4294967296)
self.assertEqual(int('a7ffda91', 17), 4294967296)
self.assertEqual(int('704he7g4', 18), 4294967296)
self.assertEqual(int('4f5aff66', 19), 4294967296)
self.assertEqual(int('3723ai4g', 20), 4294967296)
self.assertEqual(int('281d55i4', 21), 4294967296)
self.assertEqual(int('1fj8b184', 22), 4294967296)
self.assertEqual(int('1606k7ic', 23), 4294967296)
self.assertEqual(int('mb994ag', 24), 4294967296)
self.assertEqual(int('hek2mgl', 25), 4294967296)
self.assertEqual(int('dnchbnm', 26), 4294967296)
self.assertEqual(int('b28jpdm', 27), 4294967296)
self.assertEqual(int('8pfgih4', 28), 4294967296)
self.assertEqual(int('76beigg', 29), 4294967296)
self.assertEqual(int('5qmcpqg', 30), 4294967296)
self.assertEqual(int('4q0jto4', 31), 4294967296)
self.assertEqual(int('4000000', 32), 4294967296)
self.assertEqual(int('3aokq94', 33), 4294967296)
self.assertEqual(int('2qhxjli', 34), 4294967296)
self.assertEqual(int('2br45qb', 35), 4294967296)
self.assertEqual(int('1z141z4', 36), 4294967296)
# SF bug 1334662: int(string, base) wrong answers
# Checks for proper evaluation of 2**32 + 1
self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297)
self.assertEqual(int('102002022201221111212', 3), 4294967297)
self.assertEqual(int('10000000000000001', 4), 4294967297)
self.assertEqual(int('32244002423142', 5), 4294967297)
self.assertEqual(int('1550104015505', 6), 4294967297)
self.assertEqual(int('211301422355', 7), 4294967297)
self.assertEqual(int('40000000001', 8), 4294967297)
self.assertEqual(int('12068657455', 9), 4294967297)
self.assertEqual(int('4294967297', 10), 4294967297)
self.assertEqual(int('1904440555', 11), 4294967297)
self.assertEqual(int('9ba461595', 12), 4294967297)
self.assertEqual(int('535a7988a', 13), 4294967297)
self.assertEqual(int('2ca5b7465', 14), 4294967297)
self.assertEqual(int('1a20dcd82', 15), 4294967297)
self.assertEqual(int('100000001', 16), 4294967297)
self.assertEqual(int('a7ffda92', 17), 4294967297)
self.assertEqual(int('704he7g5', 18), 4294967297)
self.assertEqual(int('4f5aff67', 19), 4294967297)
self.assertEqual(int('3723ai4h', 20), 4294967297)
self.assertEqual(int('281d55i5', 21), 4294967297)
self.assertEqual(int('1fj8b185', 22), 4294967297)
self.assertEqual(int('1606k7id', 23), 4294967297)
self.assertEqual(int('mb994ah', 24), 4294967297)
self.assertEqual(int('hek2mgm', 25), 4294967297)
self.assertEqual(int('dnchbnn', 26), 4294967297)
self.assertEqual(int('b28jpdn', 27), 4294967297)
self.assertEqual(int('8pfgih5', 28), 4294967297)
self.assertEqual(int('76beigh', 29), 4294967297)
self.assertEqual(int('5qmcpqh', 30), 4294967297)
self.assertEqual(int('4q0jto5', 31), 4294967297)
self.assertEqual(int('4000001', 32), 4294967297)
self.assertEqual(int('3aokq95', 33), 4294967297)
self.assertEqual(int('2qhxjlj', 34), 4294967297)
self.assertEqual(int('2br45qc', 35), 4294967297)
self.assertEqual(int('1z141z5', 36), 4294967297)
def test_intconversion(self):
# Test __int__()
class ClassicMissingMethods:
pass
self.assertRaises(TypeError, int, ClassicMissingMethods())
class MissingMethods(object):
pass
self.assertRaises(TypeError, int, MissingMethods())
class Foo0:
def __int__(self):
return 42
class Foo1(object):
def __int__(self):
return 42
class Foo2(int):
def __int__(self):
return 42
class Foo3(int):
def __int__(self):
return self
class Foo4(int):
def __int__(self):
return 42
class Foo5(int):
def __int__(self):
return 42.
self.assertEqual(int(Foo0()), 42)
self.assertEqual(int(Foo1()), 42)
self.assertEqual(int(Foo2()), 42)
self.assertEqual(int(Foo3()), 0)
self.assertEqual(int(Foo4()), 42)
self.assertRaises(TypeError, int, Foo5())
class Classic:
pass
for base in (object, Classic):
class IntOverridesTrunc(base):
def __int__(self):
return 42
def __trunc__(self):
return -12
self.assertEqual(int(IntOverridesTrunc()), 42)
class JustTrunc(base):
def __trunc__(self):
return 42
self.assertEqual(int(JustTrunc()), 42)
for trunc_result_base in (object, Classic):
class Integral(trunc_result_base):
def __int__(self):
return 42
class TruncReturnsNonInt(base):
def __trunc__(self):
return Integral()
self.assertEqual(int(TruncReturnsNonInt()), 42)
class NonIntegral(trunc_result_base):
def __trunc__(self):
# Check that we avoid infinite recursion.
return NonIntegral()
class TruncReturnsNonIntegral(base):
def __trunc__(self):
return NonIntegral()
try:
int(TruncReturnsNonIntegral())
except TypeError as e:
self.assertEquals(str(e),
"__trunc__ returned non-Integral"
" (type NonIntegral)")
else:
self.fail("Failed to raise TypeError with %s" %
((base, trunc_result_base),))
def test_iter(self):
self.assertRaises(TypeError, iter)
self.assertRaises(TypeError, iter, 42, 42)
@ -1054,187 +599,6 @@ class BuiltinTest(unittest.TestCase):
raise ValueError
self.assertRaises(ValueError, len, BadSeq())
def test_list(self):
self.assertEqual(list([]), [])
l0_3 = [0, 1, 2, 3]
l0_3_bis = list(l0_3)
self.assertEqual(l0_3, l0_3_bis)
self.assert_(l0_3 is not l0_3_bis)
self.assertEqual(list(()), [])
self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3])
self.assertEqual(list(''), [])
self.assertEqual(list('spam'), ['s', 'p', 'a', 'm'])
if sys.maxsize == 0x7fffffff:
# This test can currently only work on 32-bit machines.
# XXX If/when PySequence_Length() returns a ssize_t, it should be
# XXX re-enabled.
# Verify clearing of bug #556025.
# This assumes that the max data size (sys.maxsize) == max
# address size this also assumes that the address size is at
# least 4 bytes with 8 byte addresses, the bug is not well
# tested
#
# Note: This test is expected to SEGV under Cygwin 1.3.12 or
# earlier due to a newlib bug. See the following mailing list
# thread for the details:
# http://sources.redhat.com/ml/newlib/2002/msg00369.html
self.assertRaises(MemoryError, list, range(sys.maxsize // 2))
# This code used to segfault in Py2.4a3
x = []
x.extend(-y for y in x)
self.assertEqual(x, [])
def test_long(self):
self.assertEqual(int(314), 314)
self.assertEqual(int(3.14), 3)
self.assertEqual(int(314), 314)
# Check that conversion from float truncates towards zero
self.assertEqual(int(-3.14), -3)
self.assertEqual(int(3.9), 3)
self.assertEqual(int(-3.9), -3)
self.assertEqual(int(3.5), 3)
self.assertEqual(int(-3.5), -3)
self.assertEqual(int("-3"), -3)
# Different base:
self.assertEqual(int("10",16), 16)
# Check conversions from string (same test set as for int(), and then some)
LL = [
('1' + '0'*20, 10**20),
('1' + '0'*100, 10**100)
]
for s, v in LL:
for sign in "", "+", "-":
for prefix in "", " ", "\t", " \t\t ":
ss = prefix + sign + s
vv = v
if sign == "-" and v is not ValueError:
vv = -v
try:
self.assertEqual(int(ss), int(vv))
except v:
pass
self.assertRaises(ValueError, int, '123\0')
self.assertRaises(ValueError, int, '53', 40)
self.assertRaises(TypeError, int, 1, 12)
# SF patch #1638879: embedded NULs were not detected with
# explicit base
self.assertRaises(ValueError, int, '123\0', 10)
self.assertRaises(ValueError, int, '123\x00 245', 20)
self.assertEqual(int('100000000000000000000000000000000', 2),
4294967296)
self.assertEqual(int('102002022201221111211', 3), 4294967296)
self.assertEqual(int('10000000000000000', 4), 4294967296)
self.assertEqual(int('32244002423141', 5), 4294967296)
self.assertEqual(int('1550104015504', 6), 4294967296)
self.assertEqual(int('211301422354', 7), 4294967296)
self.assertEqual(int('40000000000', 8), 4294967296)
self.assertEqual(int('12068657454', 9), 4294967296)
self.assertEqual(int('4294967296', 10), 4294967296)
self.assertEqual(int('1904440554', 11), 4294967296)
self.assertEqual(int('9ba461594', 12), 4294967296)
self.assertEqual(int('535a79889', 13), 4294967296)
self.assertEqual(int('2ca5b7464', 14), 4294967296)
self.assertEqual(int('1a20dcd81', 15), 4294967296)
self.assertEqual(int('100000000', 16), 4294967296)
self.assertEqual(int('a7ffda91', 17), 4294967296)
self.assertEqual(int('704he7g4', 18), 4294967296)
self.assertEqual(int('4f5aff66', 19), 4294967296)
self.assertEqual(int('3723ai4g', 20), 4294967296)
self.assertEqual(int('281d55i4', 21), 4294967296)
self.assertEqual(int('1fj8b184', 22), 4294967296)
self.assertEqual(int('1606k7ic', 23), 4294967296)
self.assertEqual(int('mb994ag', 24), 4294967296)
self.assertEqual(int('hek2mgl', 25), 4294967296)
self.assertEqual(int('dnchbnm', 26), 4294967296)
self.assertEqual(int('b28jpdm', 27), 4294967296)
self.assertEqual(int('8pfgih4', 28), 4294967296)
self.assertEqual(int('76beigg', 29), 4294967296)
self.assertEqual(int('5qmcpqg', 30), 4294967296)
self.assertEqual(int('4q0jto4', 31), 4294967296)
self.assertEqual(int('4000000', 32), 4294967296)
self.assertEqual(int('3aokq94', 33), 4294967296)
self.assertEqual(int('2qhxjli', 34), 4294967296)
self.assertEqual(int('2br45qb', 35), 4294967296)
self.assertEqual(int('1z141z4', 36), 4294967296)
self.assertEqual(int('100000000000000000000000000000001', 2),
4294967297)
self.assertEqual(int('102002022201221111212', 3), 4294967297)
self.assertEqual(int('10000000000000001', 4), 4294967297)
self.assertEqual(int('32244002423142', 5), 4294967297)
self.assertEqual(int('1550104015505', 6), 4294967297)
self.assertEqual(int('211301422355', 7), 4294967297)
self.assertEqual(int('40000000001', 8), 4294967297)
self.assertEqual(int('12068657455', 9), 4294967297)
self.assertEqual(int('4294967297', 10), 4294967297)
self.assertEqual(int('1904440555', 11), 4294967297)
self.assertEqual(int('9ba461595', 12), 4294967297)
self.assertEqual(int('535a7988a', 13), 4294967297)
self.assertEqual(int('2ca5b7465', 14), 4294967297)
self.assertEqual(int('1a20dcd82', 15), 4294967297)
self.assertEqual(int('100000001', 16), 4294967297)
self.assertEqual(int('a7ffda92', 17), 4294967297)
self.assertEqual(int('704he7g5', 18), 4294967297)
self.assertEqual(int('4f5aff67', 19), 4294967297)
self.assertEqual(int('3723ai4h', 20), 4294967297)
self.assertEqual(int('281d55i5', 21), 4294967297)
self.assertEqual(int('1fj8b185', 22), 4294967297)
self.assertEqual(int('1606k7id', 23), 4294967297)
self.assertEqual(int('mb994ah', 24), 4294967297)
self.assertEqual(int('hek2mgm', 25), 4294967297)
self.assertEqual(int('dnchbnn', 26), 4294967297)
self.assertEqual(int('b28jpdn', 27), 4294967297)
self.assertEqual(int('8pfgih5', 28), 4294967297)
self.assertEqual(int('76beigh', 29), 4294967297)
self.assertEqual(int('5qmcpqh', 30), 4294967297)
self.assertEqual(int('4q0jto5', 31), 4294967297)
self.assertEqual(int('4000001', 32), 4294967297)
self.assertEqual(int('3aokq95', 33), 4294967297)
self.assertEqual(int('2qhxjlj', 34), 4294967297)
self.assertEqual(int('2br45qc', 35), 4294967297)
self.assertEqual(int('1z141z5', 36), 4294967297)
def test_longconversion(self):
# Test __long__()
class Foo0:
def __long__(self):
return 42
class Foo1(object):
def __long__(self):
return 42
class Foo2(int):
def __long__(self):
return 42
class Foo3(int):
def __long__(self):
return self
class Foo4(int):
def __long__(self):
return 42
class Foo5(int):
def __long__(self):
return 42.
self.assertEqual(int(Foo0()), 42)
self.assertEqual(int(Foo1()), 42)
# XXX invokes __int__ now
# self.assertEqual(long(Foo2()), 42L)
self.assertEqual(int(Foo3()), 0)
# XXX likewise
# self.assertEqual(long(Foo4()), 42)
# self.assertRaises(TypeError, long, Foo5())
def test_map(self):
self.assertEqual(
list(map(lambda x: x*x, range(1,4))),
@ -1726,19 +1090,6 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(TypeError, setattr, sys, 1, 'spam')
self.assertRaises(TypeError, setattr)
def test_str(self):
self.assertEqual(str(''), '')
self.assertEqual(str(0), '0')
self.assertEqual(str(0), '0')
self.assertEqual(str(()), '()')
self.assertEqual(str([]), '[]')
self.assertEqual(str({}), '{}')
a = []
a.append(a)
self.assertEqual(str(a), '[[...]]')
a = {}
a[0] = a
self.assertEqual(str(a), '{0: {...}}')
def test_sum(self):
self.assertEqual(sum([]), 0)
@ -1761,16 +1112,6 @@ class BuiltinTest(unittest.TestCase):
raise ValueError
self.assertRaises(ValueError, sum, BadSeq())
def test_tuple(self):
self.assertEqual(tuple(()), ())
t0_3 = (0, 1, 2, 3)
t0_3_bis = tuple(t0_3)
self.assert_(t0_3 is t0_3_bis)
self.assertEqual(tuple([]), ())
self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3))
self.assertEqual(tuple(''), ())
self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm'))
def test_type(self):
self.assertEqual(type(''), type('123'))
self.assertNotEqual(type(''), type(()))

View File

@ -1,5 +1,4 @@
# Tests command line execution of scripts
from __future__ import with_statement
import unittest
import os

View File

@ -1,6 +1,5 @@
"""Unit tests for contextlib.py, and other context managers."""
from __future__ import with_statement
import sys
import os

View File

@ -23,7 +23,6 @@ or Behaviour) to test each part, or without parameter to test both parts. If
you're working through IDLE, you can import this test module and call test_main()
with the corresponding argument.
"""
from __future__ import with_statement
import glob
import math
@ -47,10 +46,12 @@ Signals = tuple(getcontext().flags.keys())
def init():
global ORIGINAL_CONTEXT
ORIGINAL_CONTEXT = getcontext().copy()
DefaultContext.prec = 9
DefaultContext.rounding = ROUND_HALF_EVEN
DefaultContext.traps = dict.fromkeys(Signals, 0)
setcontext(DefaultContext)
DefaultTestContext = Context(
prec = 9,
rounding = ROUND_HALF_EVEN,
traps = dict.fromkeys(Signals, 0)
)
setcontext(DefaultTestContext)
TESTDATADIR = 'decimaltestdata'
if __name__ == '__main__':
@ -180,8 +181,6 @@ class DecimalTest(unittest.TestCase):
"""
def setUp(self):
self.context = Context()
for key in DefaultContext.traps.keys():
DefaultContext.traps[key] = 1
self.ignore_list = ['#']
# Basically, a # means return NaN InvalidOperation.
# Different from a sNaN in trim
@ -192,13 +191,6 @@ class DecimalTest(unittest.TestCase):
'minexponent' : self.change_min_exponent,
'clamp' : self.change_clamp}
def tearDown(self):
"""Cleaning up enviroment."""
# leaving context in original state
for key in DefaultContext.traps.keys():
DefaultContext.traps[key] = 0
return
def eval_file(self, file):
global skip_expected
if skip_expected:
@ -949,8 +941,8 @@ def thfunc1(cls):
test2 = d1/d3
cls.finish1.set()
cls.assertEqual(test1, Decimal('0.333333333'))
cls.assertEqual(test2, Decimal('0.333333333'))
cls.assertEqual(test1, Decimal('0.3333333333333333333333333333'))
cls.assertEqual(test2, Decimal('0.3333333333333333333333333333'))
return
def thfunc2(cls):
@ -963,7 +955,7 @@ def thfunc2(cls):
cls.synchro.set()
cls.finish2.set()
cls.assertEqual(test1, Decimal('0.333333333'))
cls.assertEqual(test1, Decimal('0.3333333333333333333333333333'))
cls.assertEqual(test2, Decimal('0.333333333333333333'))
return

View File

@ -9,6 +9,116 @@ import operator
INF = float("inf")
NAN = float("nan")
class GeneralFloatCases(unittest.TestCase):
def test_float(self):
self.assertEqual(float(3.14), 3.14)
self.assertEqual(float(314), 314.0)
self.assertEqual(float(" 3.14 "), 3.14)
self.assertRaises(ValueError, float, " 0x3.1 ")
self.assertRaises(ValueError, float, " -0x3.p-1 ")
self.assertRaises(ValueError, float, " +0x3.p-1 ")
self.assertRaises(ValueError, float, "++3.14")
self.assertRaises(ValueError, float, "+-3.14")
self.assertRaises(ValueError, float, "-+3.14")
self.assertRaises(ValueError, float, "--3.14")
if have_unicode:
self.assertEqual(float(unicode(" 3.14 ")), 3.14)
self.assertEqual(float(unicode(" \u0663.\u0661\u0664 ",'raw-unicode-escape')), 3.14)
# Implementation limitation in PyFloat_FromString()
self.assertRaises(ValueError, float, unicode("1"*10000))
@test_support.run_with_locale('LC_NUMERIC', 'fr_FR', 'de_DE')
def test_float_with_comma(self):
# set locale to something that doesn't use '.' for the decimal point
# float must not accept the locale specific decimal point but
# it still has to accept the normal python syntac
import locale
if not locale.localeconv()['decimal_point'] == ',':
return
self.assertEqual(float(" 3.14 "), 3.14)
self.assertEqual(float("+3.14 "), 3.14)
self.assertEqual(float("-3.14 "), -3.14)
self.assertEqual(float(".14 "), .14)
self.assertEqual(float("3. "), 3.0)
self.assertEqual(float("3.e3 "), 3000.0)
self.assertEqual(float("3.2e3 "), 3200.0)
self.assertEqual(float("2.5e-1 "), 0.25)
self.assertEqual(float("5e-1"), 0.5)
self.assertRaises(ValueError, float, " 3,14 ")
self.assertRaises(ValueError, float, " +3,14 ")
self.assertRaises(ValueError, float, " -3,14 ")
self.assertRaises(ValueError, float, " 0x3.1 ")
self.assertRaises(ValueError, float, " -0x3.p-1 ")
self.assertRaises(ValueError, float, " +0x3.p-1 ")
self.assertEqual(float(" 25.e-1 "), 2.5)
self.assertEqual(fcmp(float(" .25e-1 "), .025), 0)
def test_floatconversion(self):
# Make sure that calls to __float__() work properly
class Foo0:
def __float__(self):
return 42.
class Foo1(object):
def __float__(self):
return 42.
class Foo2(float):
def __float__(self):
return 42.
class Foo3(float):
def __new__(cls, value=0.):
return float.__new__(cls, 2*value)
def __float__(self):
return self
class Foo4(float):
def __float__(self):
return 42
self.assertAlmostEqual(float(Foo0()), 42.)
self.assertAlmostEqual(float(Foo1()), 42.)
self.assertAlmostEqual(float(Foo2()), 42.)
self.assertAlmostEqual(float(Foo3(21)), 42.)
self.assertRaises(TypeError, float, Foo4(42))
def test_floatasratio(self):
for f, ratio in [
(0.875, (7, 8)),
(-0.875, (-7, 8)),
(0.0, (0, 1)),
(11.5, (23, 2)),
]:
self.assertEqual(f.as_integer_ratio(), ratio)
for i in range(10000):
f = random.random()
f *= 10 ** random.randint(-100, 100)
n, d = f.as_integer_ratio()
self.assertEqual(float(n).__truediv__(d), f)
R = fractions.Fraction
self.assertEqual(R(0, 1),
R(*float(0.0).as_integer_ratio()))
self.assertEqual(R(5, 2),
R(*float(2.5).as_integer_ratio()))
self.assertEqual(R(1, 2),
R(*float(0.5).as_integer_ratio()))
self.assertEqual(R(4728779608739021, 2251799813685248),
R(*float(2.1).as_integer_ratio()))
self.assertEqual(R(-4728779608739021, 2251799813685248),
R(*float(-2.1).as_integer_ratio()))
self.assertEqual(R(-2100, 1),
R(*float(-2100.0).as_integer_ratio()))
self.assertRaises(OverflowError, float('inf').as_integer_ratio)
self.assertRaises(OverflowError, float('-inf').as_integer_ratio)
self.assertRaises(ValueError, float('nan').as_integer_ratio)
class FormatFunctionsTestCase(unittest.TestCase):
def setUp(self):

View File

@ -1,5 +1,4 @@
# Test the frozen module defined in frozen.c.
from __future__ import with_statement
from test.test_support import captured_stdout, run_unittest
import unittest

View File

@ -271,4 +271,6 @@ def test_main(verbose=None):
run_unittest(ImportTest, PathsTests, RelativeImport)
if __name__ == '__main__':
# test needs to be a package, so we can do relative import
from test.test_import import test_main
test_main()

304
Lib/test/test_int.py Normal file
View File

@ -0,0 +1,304 @@
import sys
import unittest
from test.test_support import run_unittest
L = [
('0', 0),
('1', 1),
('9', 9),
('10', 10),
('99', 99),
('100', 100),
('314', 314),
(' 314', 314),
('314 ', 314),
(' \t\t 314 \t\t ', 314),
(repr(sys.maxsize), sys.maxsize),
(' 1x', ValueError),
(' 1 ', 1),
(' 1\02 ', ValueError),
('', ValueError),
(' ', ValueError),
(' \t\t ', ValueError)
]
class IntTestCases(unittest.TestCase):
def test_basic(self):
self.assertEqual(int(314), 314)
self.assertEqual(int(3.14), 3)
# Check that conversion from float truncates towards zero
self.assertEqual(int(-3.14), -3)
self.assertEqual(int(3.9), 3)
self.assertEqual(int(-3.9), -3)
self.assertEqual(int(3.5), 3)
self.assertEqual(int(-3.5), -3)
# Different base:
self.assertEqual(int("10",16), 16)
# Test conversion from strings and various anomalies
for s, v in L:
for sign in "", "+", "-":
for prefix in "", " ", "\t", " \t\t ":
ss = prefix + sign + s
vv = v
if sign == "-" and v is not ValueError:
vv = -v
try:
self.assertEqual(int(ss), vv)
except ValueError:
pass
s = repr(-1-sys.maxsize)
x = int(s)
self.assertEqual(x+1, -sys.maxsize)
self.assert_(isinstance(x, int))
# should return long
self.assertEqual(int(s[1:]), sys.maxsize+1)
# should return long
x = int(1e100)
self.assert_(isinstance(x, int))
x = int(-1e100)
self.assert_(isinstance(x, int))
# SF bug 434186: 0x80000000/2 != 0x80000000>>1.
# Worked by accident in Windows release build, but failed in debug build.
# Failed in all Linux builds.
x = -1-sys.maxsize
self.assertEqual(x >> 1, x//2)
self.assertRaises(ValueError, int, '123\0')
self.assertRaises(ValueError, int, '53', 40)
# SF bug 1545497: embedded NULs were not detected with
# explicit base
self.assertRaises(ValueError, int, '123\0', 10)
self.assertRaises(ValueError, int, '123\x00 245', 20)
x = int('1' * 600)
self.assert_(isinstance(x, int))
self.assertRaises(TypeError, int, 1, 12)
self.assertEqual(int('0o123', 0), 83)
self.assertEqual(int('0x123', 16), 291)
# Bug 1679: "0x" is not a valid hex literal
self.assertRaises(ValueError, int, "0x", 16)
self.assertRaises(ValueError, int, "0x", 0)
self.assertRaises(ValueError, int, "0o", 8)
self.assertRaises(ValueError, int, "0o", 0)
self.assertRaises(ValueError, int, "0b", 2)
self.assertRaises(ValueError, int, "0b", 0)
# SF bug 1334662: int(string, base) wrong answers
# Various representations of 2**32 evaluated to 0
# rather than 2**32 in previous versions
self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296)
self.assertEqual(int('102002022201221111211', 3), 4294967296)
self.assertEqual(int('10000000000000000', 4), 4294967296)
self.assertEqual(int('32244002423141', 5), 4294967296)
self.assertEqual(int('1550104015504', 6), 4294967296)
self.assertEqual(int('211301422354', 7), 4294967296)
self.assertEqual(int('40000000000', 8), 4294967296)
self.assertEqual(int('12068657454', 9), 4294967296)
self.assertEqual(int('4294967296', 10), 4294967296)
self.assertEqual(int('1904440554', 11), 4294967296)
self.assertEqual(int('9ba461594', 12), 4294967296)
self.assertEqual(int('535a79889', 13), 4294967296)
self.assertEqual(int('2ca5b7464', 14), 4294967296)
self.assertEqual(int('1a20dcd81', 15), 4294967296)
self.assertEqual(int('100000000', 16), 4294967296)
self.assertEqual(int('a7ffda91', 17), 4294967296)
self.assertEqual(int('704he7g4', 18), 4294967296)
self.assertEqual(int('4f5aff66', 19), 4294967296)
self.assertEqual(int('3723ai4g', 20), 4294967296)
self.assertEqual(int('281d55i4', 21), 4294967296)
self.assertEqual(int('1fj8b184', 22), 4294967296)
self.assertEqual(int('1606k7ic', 23), 4294967296)
self.assertEqual(int('mb994ag', 24), 4294967296)
self.assertEqual(int('hek2mgl', 25), 4294967296)
self.assertEqual(int('dnchbnm', 26), 4294967296)
self.assertEqual(int('b28jpdm', 27), 4294967296)
self.assertEqual(int('8pfgih4', 28), 4294967296)
self.assertEqual(int('76beigg', 29), 4294967296)
self.assertEqual(int('5qmcpqg', 30), 4294967296)
self.assertEqual(int('4q0jto4', 31), 4294967296)
self.assertEqual(int('4000000', 32), 4294967296)
self.assertEqual(int('3aokq94', 33), 4294967296)
self.assertEqual(int('2qhxjli', 34), 4294967296)
self.assertEqual(int('2br45qb', 35), 4294967296)
self.assertEqual(int('1z141z4', 36), 4294967296)
# tests with base 0
# this fails on 3.0, but in 2.x the old octal syntax is allowed
self.assertEqual(int(' 0o123 ', 0), 83)
self.assertEqual(int(' 0o123 ', 0), 83)
self.assertEqual(int('000', 0), 0)
self.assertEqual(int('0o123', 0), 83)
self.assertEqual(int('0x123', 0), 291)
self.assertEqual(int('0b100', 0), 4)
self.assertEqual(int(' 0O123 ', 0), 83)
self.assertEqual(int(' 0X123 ', 0), 291)
self.assertEqual(int(' 0B100 ', 0), 4)
# without base still base 10
self.assertEqual(int('0123'), 123)
self.assertEqual(int('0123', 10), 123)
# tests with prefix and base != 0
self.assertEqual(int('0x123', 16), 291)
self.assertEqual(int('0o123', 8), 83)
self.assertEqual(int('0b100', 2), 4)
self.assertEqual(int('0X123', 16), 291)
self.assertEqual(int('0O123', 8), 83)
self.assertEqual(int('0B100', 2), 4)
# the code has special checks for the first character after the
# type prefix
self.assertRaises(ValueError, int, '0b2', 2)
self.assertRaises(ValueError, int, '0b02', 2)
self.assertRaises(ValueError, int, '0B2', 2)
self.assertRaises(ValueError, int, '0B02', 2)
self.assertRaises(ValueError, int, '0o8', 8)
self.assertRaises(ValueError, int, '0o08', 8)
self.assertRaises(ValueError, int, '0O8', 8)
self.assertRaises(ValueError, int, '0O08', 8)
self.assertRaises(ValueError, int, '0xg', 16)
self.assertRaises(ValueError, int, '0x0g', 16)
self.assertRaises(ValueError, int, '0Xg', 16)
self.assertRaises(ValueError, int, '0X0g', 16)
# SF bug 1334662: int(string, base) wrong answers
# Checks for proper evaluation of 2**32 + 1
self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297)
self.assertEqual(int('102002022201221111212', 3), 4294967297)
self.assertEqual(int('10000000000000001', 4), 4294967297)
self.assertEqual(int('32244002423142', 5), 4294967297)
self.assertEqual(int('1550104015505', 6), 4294967297)
self.assertEqual(int('211301422355', 7), 4294967297)
self.assertEqual(int('40000000001', 8), 4294967297)
self.assertEqual(int('12068657455', 9), 4294967297)
self.assertEqual(int('4294967297', 10), 4294967297)
self.assertEqual(int('1904440555', 11), 4294967297)
self.assertEqual(int('9ba461595', 12), 4294967297)
self.assertEqual(int('535a7988a', 13), 4294967297)
self.assertEqual(int('2ca5b7465', 14), 4294967297)
self.assertEqual(int('1a20dcd82', 15), 4294967297)
self.assertEqual(int('100000001', 16), 4294967297)
self.assertEqual(int('a7ffda92', 17), 4294967297)
self.assertEqual(int('704he7g5', 18), 4294967297)
self.assertEqual(int('4f5aff67', 19), 4294967297)
self.assertEqual(int('3723ai4h', 20), 4294967297)
self.assertEqual(int('281d55i5', 21), 4294967297)
self.assertEqual(int('1fj8b185', 22), 4294967297)
self.assertEqual(int('1606k7id', 23), 4294967297)
self.assertEqual(int('mb994ah', 24), 4294967297)
self.assertEqual(int('hek2mgm', 25), 4294967297)
self.assertEqual(int('dnchbnn', 26), 4294967297)
self.assertEqual(int('b28jpdn', 27), 4294967297)
self.assertEqual(int('8pfgih5', 28), 4294967297)
self.assertEqual(int('76beigh', 29), 4294967297)
self.assertEqual(int('5qmcpqh', 30), 4294967297)
self.assertEqual(int('4q0jto5', 31), 4294967297)
self.assertEqual(int('4000001', 32), 4294967297)
self.assertEqual(int('3aokq95', 33), 4294967297)
self.assertEqual(int('2qhxjlj', 34), 4294967297)
self.assertEqual(int('2br45qc', 35), 4294967297)
self.assertEqual(int('1z141z5', 36), 4294967297)
def test_intconversion(self):
# Test __int__()
class ClassicMissingMethods:
pass
self.assertRaises(TypeError, int, ClassicMissingMethods())
class MissingMethods(object):
pass
self.assertRaises(TypeError, int, MissingMethods())
class Foo0:
def __int__(self):
return 42
class Foo1(object):
def __int__(self):
return 42
class Foo2(int):
def __int__(self):
return 42
class Foo3(int):
def __int__(self):
return self
class Foo4(int):
def __int__(self):
return 42
class Foo5(int):
def __int__(self):
return 42.
self.assertEqual(int(Foo0()), 42)
self.assertEqual(int(Foo1()), 42)
self.assertEqual(int(Foo2()), 42)
self.assertEqual(int(Foo3()), 0)
self.assertEqual(int(Foo4()), 42)
self.assertRaises(TypeError, int, Foo5())
class Classic:
pass
for base in (object, Classic):
class IntOverridesTrunc(base):
def __int__(self):
return 42
def __trunc__(self):
return -12
self.assertEqual(int(IntOverridesTrunc()), 42)
class JustTrunc(base):
def __trunc__(self):
return 42
self.assertEqual(int(JustTrunc()), 42)
for trunc_result_base in (object, Classic):
class Integral(trunc_result_base):
def __int__(self):
return 42
class TruncReturnsNonInt(base):
def __trunc__(self):
return Integral()
self.assertEqual(int(TruncReturnsNonInt()), 42)
class NonIntegral(trunc_result_base):
def __trunc__(self):
# Check that we avoid infinite recursion.
return NonIntegral()
class TruncReturnsNonIntegral(base):
def __trunc__(self):
return NonIntegral()
try:
int(TruncReturnsNonIntegral())
except TypeError as e:
self.assertEquals(str(e),
"__trunc__ returned non-Integral"
" (type NonIntegral)")
else:
self.fail("Failed to raise TypeError with %s" %
((base, trunc_result_base),))
def test_main():
run_unittest(IntTestCases)
if __name__ == "__main__":
test_main()

View File

@ -1161,10 +1161,10 @@ class MiscIOTest(unittest.TestCase):
def test_main():
test_support.run_unittest(IOTest, BytesIOTest, StringIOTest,
BufferedReaderTest,
BufferedWriterTest, BufferedRWPairTest,
BufferedRandomTest, TextIOWrapperTest,
MiscIOTest)
BufferedReaderTest, BufferedWriterTest,
BufferedRWPairTest, BufferedRandomTest,
StatefulIncrementalDecoderTest,
TextIOWrapperTest, MiscIOTest)
if __name__ == "__main__":
unittest.main()

View File

@ -4,6 +4,22 @@ from test import test_support, list_tests
class ListTest(list_tests.CommonTest):
type2test = list
def test_basic(self):
self.assertEqual(list([]), [])
l0_3 = [0, 1, 2, 3]
l0_3_bis = list(l0_3)
self.assertEqual(l0_3, l0_3_bis)
self.assert_(l0_3 is not l0_3_bis)
self.assertEqual(list(()), [])
self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3])
self.assertEqual(list(''), [])
self.assertEqual(list('spam'), ['s', 'p', 'a', 'm'])
# This code used to segfault in Py2.4a3
x = []
x.extend(-y for y in x)
self.assertEqual(x, [])
def test_truth(self):
super().test_truth()
self.assert_(not [])

View File

@ -1,5 +1,6 @@
import unittest
from test import test_support
import sys
import random
@ -33,6 +34,26 @@ del p2
# add complements & negations
special += [~x for x in special] + [-x for x in special]
L = [
('0', 0),
('1', 1),
('9', 9),
('10', 10),
('99', 99),
('100', 100),
('314', 314),
(' 314', 314),
('314 ', 314),
(' \t\t 314 \t\t ', 314),
(repr(sys.maxsize), sys.maxsize),
(' 1x', ValueError),
(' 1 ', 1),
(' 1\02 ', ValueError),
('', ValueError),
(' ', ValueError),
(' \t\t ', ValueError)
]
class LongTest(unittest.TestCase):
@ -229,8 +250,206 @@ class LongTest(unittest.TestCase):
x = self.getran(lenx)
self.check_format_1(x)
def test_long(self):
self.assertEqual(int(314), 314)
self.assertEqual(int(3.14), 3)
self.assertEqual(int(314), 314)
# Check that conversion from float truncates towards zero
self.assertEqual(int(-3.14), -3)
self.assertEqual(int(3.9), 3)
self.assertEqual(int(-3.9), -3)
self.assertEqual(int(3.5), 3)
self.assertEqual(int(-3.5), -3)
self.assertEqual(int("-3"), -3)
# Different base:
self.assertEqual(int("10",16), 16)
# Check conversions from string (same test set as for int(), and then some)
LL = [
('1' + '0'*20, 10**20),
('1' + '0'*100, 10**100)
]
L2 = L[:]
for s, v in L2 + LL:
for sign in "", "+", "-":
for prefix in "", " ", "\t", " \t\t ":
ss = prefix + sign + s
vv = v
if sign == "-" and v is not ValueError:
vv = -v
try:
self.assertEqual(int(ss), int(vv))
except ValueError:
pass
self.assertRaises(ValueError, int, '123\0')
self.assertRaises(ValueError, int, '53', 40)
self.assertRaises(TypeError, int, 1, 12)
# SF patch #1638879: embedded NULs were not detected with
# explicit base
self.assertRaises(ValueError, int, '123\0', 10)
self.assertRaises(ValueError, int, '123\x00 245', 20)
self.assertEqual(int('100000000000000000000000000000000', 2),
4294967296)
self.assertEqual(int('102002022201221111211', 3), 4294967296)
self.assertEqual(int('10000000000000000', 4), 4294967296)
self.assertEqual(int('32244002423141', 5), 4294967296)
self.assertEqual(int('1550104015504', 6), 4294967296)
self.assertEqual(int('211301422354', 7), 4294967296)
self.assertEqual(int('40000000000', 8), 4294967296)
self.assertEqual(int('12068657454', 9), 4294967296)
self.assertEqual(int('4294967296', 10), 4294967296)
self.assertEqual(int('1904440554', 11), 4294967296)
self.assertEqual(int('9ba461594', 12), 4294967296)
self.assertEqual(int('535a79889', 13), 4294967296)
self.assertEqual(int('2ca5b7464', 14), 4294967296)
self.assertEqual(int('1a20dcd81', 15), 4294967296)
self.assertEqual(int('100000000', 16), 4294967296)
self.assertEqual(int('a7ffda91', 17), 4294967296)
self.assertEqual(int('704he7g4', 18), 4294967296)
self.assertEqual(int('4f5aff66', 19), 4294967296)
self.assertEqual(int('3723ai4g', 20), 4294967296)
self.assertEqual(int('281d55i4', 21), 4294967296)
self.assertEqual(int('1fj8b184', 22), 4294967296)
self.assertEqual(int('1606k7ic', 23), 4294967296)
self.assertEqual(int('mb994ag', 24), 4294967296)
self.assertEqual(int('hek2mgl', 25), 4294967296)
self.assertEqual(int('dnchbnm', 26), 4294967296)
self.assertEqual(int('b28jpdm', 27), 4294967296)
self.assertEqual(int('8pfgih4', 28), 4294967296)
self.assertEqual(int('76beigg', 29), 4294967296)
self.assertEqual(int('5qmcpqg', 30), 4294967296)
self.assertEqual(int('4q0jto4', 31), 4294967296)
self.assertEqual(int('4000000', 32), 4294967296)
self.assertEqual(int('3aokq94', 33), 4294967296)
self.assertEqual(int('2qhxjli', 34), 4294967296)
self.assertEqual(int('2br45qb', 35), 4294967296)
self.assertEqual(int('1z141z4', 36), 4294967296)
self.assertEqual(int('100000000000000000000000000000001', 2),
4294967297)
self.assertEqual(int('102002022201221111212', 3), 4294967297)
self.assertEqual(int('10000000000000001', 4), 4294967297)
self.assertEqual(int('32244002423142', 5), 4294967297)
self.assertEqual(int('1550104015505', 6), 4294967297)
self.assertEqual(int('211301422355', 7), 4294967297)
self.assertEqual(int('40000000001', 8), 4294967297)
self.assertEqual(int('12068657455', 9), 4294967297)
self.assertEqual(int('4294967297', 10), 4294967297)
self.assertEqual(int('1904440555', 11), 4294967297)
self.assertEqual(int('9ba461595', 12), 4294967297)
self.assertEqual(int('535a7988a', 13), 4294967297)
self.assertEqual(int('2ca5b7465', 14), 4294967297)
self.assertEqual(int('1a20dcd82', 15), 4294967297)
self.assertEqual(int('100000001', 16), 4294967297)
self.assertEqual(int('a7ffda92', 17), 4294967297)
self.assertEqual(int('704he7g5', 18), 4294967297)
self.assertEqual(int('4f5aff67', 19), 4294967297)
self.assertEqual(int('3723ai4h', 20), 4294967297)
self.assertEqual(int('281d55i5', 21), 4294967297)
self.assertEqual(int('1fj8b185', 22), 4294967297)
self.assertEqual(int('1606k7id', 23), 4294967297)
self.assertEqual(int('mb994ah', 24), 4294967297)
self.assertEqual(int('hek2mgm', 25), 4294967297)
self.assertEqual(int('dnchbnn', 26), 4294967297)
self.assertEqual(int('b28jpdn', 27), 4294967297)
self.assertEqual(int('8pfgih5', 28), 4294967297)
self.assertEqual(int('76beigh', 29), 4294967297)
self.assertEqual(int('5qmcpqh', 30), 4294967297)
self.assertEqual(int('4q0jto5', 31), 4294967297)
self.assertEqual(int('4000001', 32), 4294967297)
self.assertEqual(int('3aokq95', 33), 4294967297)
self.assertEqual(int('2qhxjlj', 34), 4294967297)
self.assertEqual(int('2br45qc', 35), 4294967297)
self.assertEqual(int('1z141z5', 36), 4294967297)
def test_conversion(self):
# Test __long__()
class ClassicMissingMethods:
pass
self.assertRaises(TypeError, int, ClassicMissingMethods())
class MissingMethods(object):
pass
self.assertRaises(TypeError, int, MissingMethods())
class Foo0:
def __int__(self):
return 42
class Foo1(object):
def __int__(self):
return 42
class Foo2(int):
def __int__(self):
return 42
class Foo3(int):
def __int__(self):
return self
class Foo4(int):
def __int__(self):
return 42
class Foo5(int):
def __int__(self):
return 42.
self.assertEqual(int(Foo0()), 42)
self.assertEqual(int(Foo1()), 42)
self.assertEqual(int(Foo2()), 42)
self.assertEqual(int(Foo3()), 0)
self.assertEqual(int(Foo4()), 42)
self.assertRaises(TypeError, int, Foo5())
class Classic:
pass
for base in (object, Classic):
class LongOverridesTrunc(base):
def __long__(self):
return 42
def __trunc__(self):
return -12
self.assertEqual(int(LongOverridesTrunc()), 42)
class JustTrunc(base):
def __trunc__(self):
return 42
self.assertEqual(int(JustTrunc()), 42)
for trunc_result_base in (object, Classic):
class Integral(trunc_result_base):
def __int__(self):
return 42
class TruncReturnsNonLong(base):
def __trunc__(self):
return Integral()
self.assertEqual(int(TruncReturnsNonLong()), 42)
class NonIntegral(trunc_result_base):
def __trunc__(self):
# Check that we avoid infinite recursion.
return NonIntegral()
class TruncReturnsNonIntegral(base):
def __trunc__(self):
return NonIntegral()
try:
int(TruncReturnsNonIntegral())
except TypeError as e:
self.assertEquals(str(e),
"__trunc__ returned non-Integral"
" (type NonIntegral)")
else:
self.fail("Failed to raise TypeError with %s" %
((base, trunc_result_base),))
def test_misc(self):
import sys
# check the extremes in int<->long conversion
hugepos = sys.maxsize
@ -403,7 +622,6 @@ class LongTest(unittest.TestCase):
def test_mixed_compares(self):
eq = self.assertEqual
import math
import sys
# We're mostly concerned with that mixing floats and longs does the
# right stuff, even when longs are too large to fit in a float.

View File

@ -8,40 +8,23 @@ import warnings
class TestUntestedModules(unittest.TestCase):
def test_at_least_import_untested_modules(self):
with test_support.catch_warning():
import BaseHTTPServer
import DocXMLRPCServer
import CGIHTTPServer
import SimpleHTTPServer
import SimpleXMLRPCServer
import aifc
import bdb
import cgitb
import cmd
import code
import compileall
import distutils.archive_util
import distutils.bcppcompiler
import distutils.ccompiler
import distutils.cmd
import distutils.core
import distutils.cygwinccompiler
import distutils.dep_util
import distutils.dir_util
import distutils.emxccompiler
import distutils.errors
import distutils.extension
import distutils.file_util
import distutils.filelist
import distutils.log
if sys.platform.startswith('win'):
import distutils.msvccompiler
import distutils.mwerkscompiler
import distutils.sysconfig
import distutils.text_file
import distutils.unixccompiler
import distutils.util
import distutils.version
import distutils.command.bdist_dumb
if sys.platform.startswith('win'):
@ -52,23 +35,18 @@ class TestUntestedModules(unittest.TestCase):
import distutils.command.build_clib
import distutils.command.build_ext
import distutils.command.build
import distutils.command.build_py
import distutils.command.build_scripts
import distutils.command.clean
import distutils.command.config
import distutils.command.install_data
import distutils.command.install_egg_info
import distutils.command.install_headers
import distutils.command.install_lib
import distutils.command.install
import distutils.command.install_scripts
import distutils.command.register
import distutils.command.sdist
import distutils.command.upload
import encodings
import formatter
import ftplib
import getpass
import htmlentitydefs
import ihooks
@ -78,7 +56,6 @@ class TestUntestedModules(unittest.TestCase):
import linecache
import macurl2path
import mailcap
import mutex
import nntplib
import nturl2path
import opcode
@ -88,14 +65,12 @@ class TestUntestedModules(unittest.TestCase):
import py_compile
import rlcompleter
import sched
import smtplib
import sndhdr
import statvfs
import sunau
import sunaudio
import symbol
import tabnanny
import telnetlib
import timeit
import token
try:

View File

@ -473,8 +473,10 @@ def captured_output(stream_name):
import io
orig_stdout = getattr(sys, stream_name)
setattr(sys, stream_name, io.StringIO())
yield getattr(sys, stream_name)
setattr(sys, stream_name, orig_stdout)
try:
yield getattr(sys, stream_name)
finally:
setattr(sys, stream_name, orig_stdout)
def captured_stdout():
return captured_output("stdout")

View File

@ -129,6 +129,10 @@ What a mess!
expect = ['And she said, "Go to hell!" Can you believe that?']
self.check(wrapper.wrap(text), expect)
text = 'File stdio.h is nice.'
expect = ['File stdio.h is nice.']
self.check(wrapper.wrap(text), expect)
def test_wrap_short(self):
# Wrapping to make short lines longer

View File

@ -4,6 +4,7 @@ from test import test_support
import unittest
import sys
import difflib
import gc
# A very basic example. If this fails, we're in deep trouble.
def basic():
@ -244,6 +245,17 @@ class Tracer:
return self.trace
class TraceTestCase(unittest.TestCase):
# Disable gc collection when tracing, otherwise the
# deallocators may be traced as well.
def setUp(self):
self.using_gc = gc.isenabled()
gc.disable()
def tearDown(self):
if self.using_gc:
gc.enable()
def compare_events(self, line_offset, events, expected_events):
events = [(l - line_offset, e) for (l, e) in events]
if events != expected_events:

View File

@ -1,10 +1,24 @@
"""Test cases for traceback module"""
from _testcapi import traceback_print
from io import StringIO
import sys
import unittest
from test.test_support import run_unittest, is_jython
from test.test_support import run_unittest, is_jython, Error
import traceback
try:
raise KeyError
except KeyError:
type_, value, tb = sys.exc_info()
file_ = StringIO()
traceback_print(tb, file_)
example_traceback = file_.getvalue()
else:
raise Error("unable to create test traceback string")
class TracebackCases(unittest.TestCase):
# For now, a very minimal set of tests. I want to be sure that
# formatting of SyntaxErrors works based on changes for 2.1.
@ -76,8 +90,20 @@ class TracebackCases(unittest.TestCase):
self.assertEqual(err, ['None\n'])
class TracebackFormatTests(unittest.TestCase):
def test_traceback_indentation(self):
# Make sure that the traceback is properly indented.
tb_lines = example_traceback.splitlines()
self.assertEquals(len(tb_lines), 3)
banner, location, source_line = tb_lines
self.assert_(banner.startswith('Traceback'))
self.assert_(location.startswith(' File'))
self.assert_(source_line.startswith('raise'))
def test_main():
run_unittest(TracebackCases)
run_unittest(TracebackCases, TracebackFormatTests)
if __name__ == "__main__":

View File

@ -7,6 +7,13 @@ class TupleTest(seq_tests.CommonTest):
super().test_len()
# calling built-in types without argument must return empty
self.assertEqual(tuple(), ())
t0_3 = (0, 1, 2, 3)
t0_3_bis = tuple(t0_3)
self.assert_(t0_3 is t0_3_bis)
self.assertEqual(tuple([]), ())
self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3))
self.assertEqual(tuple(''), ())
self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm'))
def test_truth(self):
super().test_truth()

View File

@ -1059,6 +1059,12 @@ class MiscTests(unittest.TestCase):
o = build_opener(urllib2.HTTPHandler())
self.opener_has_handler(o, urllib2.HTTPHandler)
# Issue2670: multiple handlers sharing the same base class
class MyOtherHTTPHandler(urllib2.HTTPHandler): pass
o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
self.opener_has_handler(o, MyHTTPHandler)
self.opener_has_handler(o, MyOtherHTTPHandler)
def opener_has_handler(self, opener, handler_class):
for h in opener.handlers:
if h.__class__ == handler_class:

View File

@ -229,6 +229,77 @@ class WarnTests(unittest.TestCase):
warning_tests.inner("spam7", stacklevel=9999)
self.assertEqual(os.path.basename(w.filename), "sys")
def test_missing_filename_not_main(self):
# If __file__ is not specified and __main__ is not the module name,
# then __file__ should be set to the module name.
filename = warning_tests.__file__
try:
del warning_tests.__file__
with warnings_state(self.module):
with test_support.catch_warning(self.module) as w:
warning_tests.inner("spam8", stacklevel=1)
self.assertEqual(w.filename, warning_tests.__name__)
finally:
warning_tests.__file__ = filename
def test_missing_filename_main_with_argv(self):
# If __file__ is not specified and the caller is __main__ and sys.argv
# exists, then use sys.argv[0] as the file.
if not hasattr(sys, 'argv'):
return
filename = warning_tests.__file__
module_name = warning_tests.__name__
try:
del warning_tests.__file__
warning_tests.__name__ = '__main__'
with warnings_state(self.module):
with test_support.catch_warning(self.module) as w:
warning_tests.inner('spam9', stacklevel=1)
self.assertEqual(w.filename, sys.argv[0])
finally:
warning_tests.__file__ = filename
warning_tests.__name__ = module_name
def test_missing_filename_main_without_argv(self):
# If __file__ is not specified, the caller is __main__, and sys.argv
# is not set, then '__main__' is the file name.
filename = warning_tests.__file__
module_name = warning_tests.__name__
argv = sys.argv
try:
del warning_tests.__file__
warning_tests.__name__ = '__main__'
del sys.argv
with warnings_state(self.module):
with test_support.catch_warning(self.module) as w:
warning_tests.inner('spam10', stacklevel=1)
self.assertEqual(w.filename, '__main__')
finally:
warning_tests.__file__ = filename
warning_tests.__name__ = module_name
sys.argv = argv
def BROKEN_test_missing_filename_main_with_argv_empty_string(self):
# If __file__ is not specified, the caller is __main__, and sys.argv[0]
# is the empty string, then '__main__ is the file name.
# Tests issue 2743.
file_name = warning_tests.__file__
module_name = warning_tests.__name__
argv = sys.argv
try:
del warning_tests.__file__
warning_tests.__name__ = '__main__'
sys.argv = ['']
with warnings_state(self.module):
with test_support.catch_warning(self.module) as w:
warning_tests.inner('spam11', stacklevel=1)
self.assertEqual(w.filename, '__main__')
finally:
warning_tests.__file__ = file_name
warning_tests.__name__ = module_name
sys.argv = argv
class CWarnTests(BaseTest, WarnTests):
module = c_warnings

View File

@ -2,7 +2,6 @@
"""Unit tests for the with statement specified in PEP 343."""
from __future__ import with_statement
__author__ = "Mike Bland"
__email__ = "mbland at acm dot org"

View File

@ -50,7 +50,7 @@ class XMLRPCTestCase(unittest.TestCase):
self.assertEquals(newdt, xmlrpclib.DateTime('20050210T11:41:23'))
def test_datetime_before_1900(self):
# same as before but with an date before 1900
# same as before but with a date before 1900
dt = datetime.datetime(1, 2, 10, 11, 41, 23)
s = xmlrpclib.dumps((dt,))
(newdt,), m = xmlrpclib.loads(s, use_datetime=1)

View File

@ -79,7 +79,7 @@ class TextWrapper:
sentence_end_re = re.compile(r'[a-z]' # lowercase letter
r'[\.\!\?]' # sentence-ending punct.
r'[\"\']?' # optional end-of-quote
)
r'\Z') # end of chunk
def __init__(self,

View File

@ -443,14 +443,14 @@ def build_opener(*handlers):
FTPHandler, FileHandler, HTTPErrorProcessor]
if hasattr(httplib, 'HTTPS'):
default_classes.append(HTTPSHandler)
skip = []
skip = set()
for klass in default_classes:
for check in handlers:
if isclass(check):
if issubclass(check, klass):
skip.append(klass)
skip.add(klass)
elif isinstance(check, klass):
skip.append(klass)
skip.add(klass)
for klass in skip:
default_classes.remove(klass)

View File

@ -2,7 +2,7 @@
This module is an implementation of PEP 205:
http://python.sourceforge.net/peps/pep-0205.html
http://www.python.org/dev/peps/pep-0205/
"""
# Naming convention: Variables named "wr" are weak reference objects;

View File

@ -199,7 +199,7 @@ PKG_RECIPES = [
dict(
name="PythonApplications",
long_name="GUI Applications",
source="/Applications/MacPython %(VER)s",
source="/Applications/Python %(VER)s",
readme="""\
This package installs IDLE (an interactive Python IDE),
Python Launcher and Build Applet (create application bundles

View File

@ -19,7 +19,7 @@ environment, an applet builder), plus a set of pre-built
extension modules that open up specific Macintosh technologies
to Python programs (Carbon, AppleScript, Quicktime, more).
The installer puts the applications in "MacPython $VERSION"
The installer puts the applications in "Python $VERSION"
in your Applications folder, command-line tools in
/usr/local/bin and the underlying machinery in
$PYTHONFRAMEWORKINSTALLDIR.

View File

@ -9,6 +9,7 @@ srcdir= @srcdir@
VERSION= @VERSION@
UNIVERSALSDK=@UNIVERSALSDK@
builddir= ../..
PYTHONFRAMEWORK=@PYTHONFRAMEWORK@
RUNSHARED= @RUNSHARED@
BUILDEXE= @BUILDEXEEXT@
@ -21,7 +22,7 @@ MACOSX_DEPLOYMENT_TARGET=@CONFIGURE_MACOSX_DEPLOYMENT_TARGET@
BUNDLEBULDER=$(srcdir)/../../Lib/plat-mac/bundlebuilder.py
PYTHONAPPSDIR=/Applications/MacPython $(VERSION)
PYTHONAPPSDIR=/Applications/$(PYTHONFRAMEWORK) $(VERSION)
all: IDLE.app

View File

@ -13,14 +13,16 @@ BUILDPYTHON=$(builddir)/python$(BUILDEXE)
DESTDIR=
LDFLAGS=@LDFLAGS@
FRAMEWORKUNIXTOOLSPREFIX=@FRAMEWORKUNIXTOOLSPREFIX@
PYTHONFRAMEWORK=@PYTHONFRAMEWORK@
# These are normally glimpsed from the previous set
bindir=$(prefix)/bin
PYTHONAPPSDIR=/Applications/MacPython $(VERSION)
PYTHONAPPSDIR=/Applications/$(PYTHONFRAMEWORK) $(VERSION)
APPINSTALLDIR=$(prefix)/Resources/Python.app
# Variables for installing the "normal" unix binaries
INSTALLED_PYTHONAPP=$(APPINSTALLDIR)/Contents/MacOS/Python
INSTALLED_PYTHONAPP=$(APPINSTALLDIR)/Contents/MacOS/$(PYTHONFRAMEWORK)
# Items more-or-less copied from the main Makefile
DIRMODE=755
@ -103,7 +105,7 @@ install_versionedtools:
pythonw: $(srcdir)/Tools/pythonw.c Makefile
$(CC) $(LDFLAGS) -o $@ $(srcdir)/Tools/pythonw.c \
-DPYTHONWEXECUTABLE='"$(APPINSTALLDIR)/Contents/MacOS/Python"'
-DPYTHONWEXECUTABLE='"$(APPINSTALLDIR)/Contents/MacOS/$(PYTHONFRAMEWORK)"'
install_PythonLauncher:
@ -155,7 +157,7 @@ install_Python:
esac; \
done; \
done
$(INSTALL_PROGRAM) $(STRIPFLAG) $(BUILDPYTHON) "$(DESTDIR)$(APPINSTALLDIR)/Contents/MacOS/Python"
$(INSTALL_PROGRAM) $(STRIPFLAG) $(BUILDPYTHON) "$(DESTDIR)$(APPINSTALLDIR)/Contents/MacOS/$(PYTHONFRAMEWORK)"
install_IDLE:
cd IDLE && make install

View File

@ -12,6 +12,7 @@ builddir= ../..
RUNSHARED= @RUNSHARED@
BUILDEXE= @BUILDEXEEXT@
BUILDPYTHON= $(builddir)/python$(BUILDEXE)
PYTHONFRAMEWORK=@PYTHONFRAMEWORK@
# Deployment target selected during configure, to be checked
# by distutils
@ -20,7 +21,7 @@ MACOSX_DEPLOYMENT_TARGET=@CONFIGURE_MACOSX_DEPLOYMENT_TARGET@
BUNDLEBULDER=$(srcdir)/../../Lib/plat-mac/bundlebuilder.py
PYTHONAPPSDIR=/Applications/MacPython $(VERSION)
PYTHONAPPSDIR=/Applications/$(PYTHONFRAMEWORK) $(VERSION)
OBJECTS=FileSettings.o MyAppDelegate.o MyDocument.o PreferencesWindowController.o doscript.o main.o
all: Python\ Launcher.app

View File

@ -121,8 +121,8 @@
return YES;
} else {
[self run];
[self close];
return NO;
[self performSelector:@selector(close) withObject:nil afterDelay:0.0];
return YES;
}
}

View File

@ -11,108 +11,49 @@
#import <ApplicationServices/ApplicationServices.h>
#import "doscript.h"
/* I assume I could pick these up from somewhere, but where... */
#define CREATOR 'trmx'
#define ACTIVATE_CMD 'misc'
#define ACTIVATE_SUITE 'actv'
#define DOSCRIPT_CMD 'dosc'
#define DOSCRIPT_SUITE 'core'
#define WITHCOMMAND 'cmnd'
/* ... and there's probably also a better way to do this... */
#define START_TERMINAL "/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal &"
extern int
doscript(const char *command)
{
OSErr err;
AppleEvent theAEvent, theReply;
AEAddressDesc terminalAddress;
AEDesc commandDesc;
OSType terminalCreator = CREATOR;
/* set up locals */
AECreateDesc(typeNull, NULL, 0, &theAEvent);
AECreateDesc(typeNull, NULL, 0, &terminalAddress);
AECreateDesc(typeNull, NULL, 0, &theReply);
AECreateDesc(typeNull, NULL, 0, &commandDesc);
/* create the "activate" event for Terminal */
err = AECreateDesc(typeApplSignature, (Ptr) &terminalCreator,
sizeof(terminalCreator), &terminalAddress);
if (err != noErr) {
NSLog(@"doscript: AECreateDesc: error %d\n", err);
goto bail;
}
err = AECreateAppleEvent(ACTIVATE_SUITE, ACTIVATE_CMD,
&terminalAddress, kAutoGenerateReturnID,
kAnyTransactionID, &theAEvent);
if (err != noErr) {
NSLog(@"doscript: AECreateAppleEvent(activate): error %d\n", err);
goto bail;
}
/* send the event */
err = AESend(&theAEvent, &theReply, kAEWaitReply,
kAENormalPriority, kAEDefaultTimeout, NULL, NULL);
if ( err == -600 ) {
int count=10;
/* If it failed with "no such process" try to start Terminal */
err = system(START_TERMINAL);
if ( err ) {
NSLog(@"doscript: system(): %s\n", strerror(errno));
goto bail;
}
do {
sleep(1);
/* send the event again */
err = AESend(&theAEvent, &theReply, kAEWaitReply,
kAENormalPriority, kAEDefaultTimeout, NULL, NULL);
} while (err == -600 && --count > 0);
if ( err == -600 )
NSLog(@"doscript: Could not activate Terminal\n");
}
if (err != noErr) {
NSLog(@"doscript: AESend(activate): error %d\n", err);
goto bail;
}
/* create the "doscript with command" event for Terminal */
err = AECreateAppleEvent(DOSCRIPT_SUITE, DOSCRIPT_CMD,
&terminalAddress, kAutoGenerateReturnID,
kAnyTransactionID, &theAEvent);
if (err != noErr) {
NSLog(@"doscript: AECreateAppleEvent(doscript): error %d\n", err);
goto bail;
}
/* add the command to the apple event */
err = AECreateDesc(typeChar, command, strlen(command), &commandDesc);
if (err != noErr) {
NSLog(@"doscript: AECreateDesc(command): error %d\n", err);
goto bail;
}
err = AEPutParamDesc(&theAEvent, WITHCOMMAND, &commandDesc);
if (err != noErr) {
NSLog(@"doscript: AEPutParamDesc: error %d\n", err);
goto bail;
}
char *bundleID = "com.apple.Terminal";
AppleEvent evt, res;
AEDesc desc;
OSStatus err;
/* send the command event to Terminal.app */
err = AESend(&theAEvent, &theReply, kAEWaitReply,
kAENormalPriority, kAEDefaultTimeout, NULL, NULL);
if (err != noErr) {
NSLog(@"doscript: AESend(docommand): error %d\n", err);
goto bail;
}
/* clean up and leave */
bail:
AEDisposeDesc(&commandDesc);
AEDisposeDesc(&theAEvent);
AEDisposeDesc(&terminalAddress);
AEDisposeDesc(&theReply);
return err;
[[NSWorkspace sharedWorkspace] launchApplication:@"/Applications/Utilities/Terminal.app/"];
// Build event
err = AEBuildAppleEvent(kAECoreSuite, kAEDoScript,
typeApplicationBundleID,
bundleID, strlen(bundleID),
kAutoGenerateReturnID,
kAnyTransactionID,
&evt, NULL,
"'----':utf8(@)", strlen(command),
command);
if (err) {
NSLog(@"AEBuildAppleEvent failed: %d\n", err);
return err;
}
// Send event and check for any Apple Event Manager errors
err = AESendMessage(&evt, &res, kAEWaitReply, kAEDefaultTimeout);
AEDisposeDesc(&evt);
if (err) {
NSLog(@"AESendMessage failed: %d\n", err);
return err;
}
// Check for any application errors
err = AEGetParamDesc(&res, keyErrorNumber, typeSInt32, &desc);
AEDisposeDesc(&res);
if (!err) {
AEGetDescData(&desc, &err, sizeof(err));
NSLog(@"Terminal returned an error: %d", err);
AEDisposeDesc(&desc);
} else if (err == errAEDescNotFound) {
err = noErr;
} else {
NSLog(@"AEGetPArmDesc returned an error: %d", err);
}
return err;
}

View File

@ -20,7 +20,7 @@
<key>CFBundleExecutable</key>
<string>Python</string>
<key>CFBundleGetInfoString</key>
<string>2.5alpha0, (c) 2004 Python Software Foundation.</string>
<string>@VERSION@, (c) 2004 Python Software Foundation.</string>
<key>CFBundleHelpBookFolder</key>
<array>
<string>Documentation</string>
@ -33,21 +33,21 @@
<key>CFBundleIconFile</key>
<string>PythonInterpreter.icns</string>
<key>CFBundleIdentifier</key>
<string>org.python.python</string>
<string>@PYTHONFRAMEWORKIDENTIFIER@.app</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>2.5alpha0, (c) 2004 Python Software Foundation.</string>
<string>@VERSION@, (c) 2004-2008 Python Software Foundation.</string>
<key>CFBundleName</key>
<string>Python</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>2.5alpha0</string>
<string>@VERSION@</string>
<key>CFBundleSignature</key>
<string>PytX</string>
<key>CFBundleVersion</key>
<string>2.5alpha0</string>
<string>@VERSION@</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>LSRequiresCarbon</key>

View File

@ -9,7 +9,7 @@
<key>CFBundleGetInfoString</key>
<string>Python Runtime and Library</string>
<key>CFBundleIdentifier</key>
<string>org.python.python</string>
<string>@PYTHONFRAMEWORKIDENTIFIER@</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
@ -17,10 +17,12 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.5</string>
<string>%VERSION%, (c) 2004-2008 Python Software Foundation.</string>
<key>CFBundleLongVersionString</key>
<string>%VERSION%, (c) 2004-2008 Python Software Foundation.</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>2.5</string>
<string>%VERSION%</string>
</dict>
</plist>

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildVersion</key>
<string>1</string>
<key>CFBundleShortVersionString</key>
<string>2.5alpha0</string>
<key>CFBundleVersion</key>
<string>2.5alpha0</string>
<key>ProjectName</key>
<string>Python</string>
<key>ReleaseStatus</key>
<string>alfa</string>
<key>SourceVersion</key>
<string>2.4a0</string>
</dict>
</plist>

View File

@ -416,18 +416,16 @@ libpython$(VERSION).sl: $(LIBRARY_OBJS)
# This rule is here for OPENSTEP/Rhapsody/MacOSX. It builds a temporary
# minimal framework (not including the Lib directory and such) in the current
# directory.
RESSRCDIR=$(srcdir)/Mac/Resources/framework
RESSRCDIR=Mac/Resources/framework
$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK): \
$(LIBRARY) \
$(RESSRCDIR)/Info.plist \
$(RESSRCDIR)/version.plist \
$(RESSRCDIR)/English.lproj/InfoPlist.strings
$(RESSRCDIR)/Info.plist
$(INSTALL) -d -m $(DIRMODE) $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)
if test "${UNIVERSALSDK}"; then \
$(CC) -o $(LDLIBRARY) -arch i386 -arch ppc -dynamiclib \
-isysroot "${UNIVERSALSDK}" \
-all_load $(LIBRARY) -Wl,-single_module \
-install_name $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/Python \
-install_name $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK) \
-compatibility_version $(VERSION) \
-current_version $(VERSION); \
else \
@ -438,10 +436,6 @@ $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK): \
$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/English.lproj
$(INSTALL_DATA) $(RESSRCDIR)/Info.plist \
$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/Info.plist
$(INSTALL_DATA) $(RESSRCDIR)/version.plist \
$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/version.plist
$(INSTALL_DATA) $(RESSRCDIR)/English.lproj/InfoPlist.strings \
$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/English.lproj/InfoPlist.strings
$(LN) -fsn $(VERSION) $(PYTHONFRAMEWORKDIR)/Versions/Current
$(LN) -fsn Versions/Current/$(PYTHONFRAMEWORK) $(PYTHONFRAMEWORKDIR)/$(PYTHONFRAMEWORK)
$(LN) -fsn Versions/Current/Headers $(PYTHONFRAMEWORKDIR)/Headers
@ -1022,12 +1016,9 @@ frameworkinstallstructure: $(LDLIBRARY)
fi; \
done
$(LN) -fsn include/python$(VERSION) $(DESTDIR)$(prefix)/Headers
$(INSTALL_DATA) $(RESSRCDIR)/Info.plist $(DESTDIR)$(prefix)/Resources/Info.plist
$(INSTALL_DATA) $(RESSRCDIR)/version.plist $(DESTDIR)$(prefix)/Resources/version.plist
$(INSTALL_DATA) $(RESSRCDIR)/English.lproj/InfoPlist.strings \
$(DESTDIR)$(prefix)/Resources/English.lproj/InfoPlist.strings
sed 's/%VERSION%/'"`$(RUNSHARED) ./$(BUILDPYTHON) -c 'import platform; print platform.python_version()'`"'/g' < $(RESSRCDIR)/Info.plist > $(DESTDIR)$(prefix)/Resources/Info.plist
$(LN) -fsn $(VERSION) $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Versions/Current
$(LN) -fsn Versions/Current/Python $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Python
$(LN) -fsn Versions/Current/$(PYTHONFRAMEWORK) $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/$(PYTHONFRAMEWORK)
$(LN) -fsn Versions/Current/Headers $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Headers
$(LN) -fsn Versions/Current/Resources $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Resources
$(INSTALL_SHARED) $(LDLIBRARY) $(DESTDIR)$(PYTHONFRAMEWORKPREFIX)/$(LDLIBRARY)
@ -1036,7 +1027,7 @@ frameworkinstallstructure: $(LDLIBRARY)
# Install a number of symlinks to keep software that expects a normal unix
# install (which includes python-config) happy.
frameworkinstallmaclib:
ln -fs "../../../Python" "$(DESTDIR)$(prefix)/lib/python$(VERSION)/config/libpython$(VERSION).a"
ln -fs "../../../$(PYTHONFRAMEWORK)" "$(DESTDIR)$(prefix)/lib/python$(VERSION)/config/libpython$(VERSION).a"
cd Mac && $(MAKE) installmacsubtree DESTDIR="$(DESTDIR)"
# This installs the IDE, the Launcher and other apps into /Applications

View File

@ -17,6 +17,21 @@ the format to accommodate documentation needs as they arise.
Permissions History
-------------------
- Rodrigo Bernardo Pimentel was given SVN access on 29 April 2008 by MvL,
for GSoC contributions.
- Heiko Weinen was given SVN access on 29 April 2008 by MvL,
for GSoC contributions.
- Jesus Cea was was given SVN access on 24 April 2008 by MvL,
for maintenance of bsddb.
- Guilherme Polo was given SVN access on 24 April 2008 by MvL,
for GSoC contributions.
- Thomas Lee was given SVN access on 21 April 2008 by NCN,
for work on branches (ast/optimizer related).
- Jeroen Ruigrok van der Werven was given SVN access on 12 April 2008
by Georg Brandl, for documentation work.

View File

@ -409,6 +409,115 @@ CDataType_from_address(PyObject *type, PyObject *value)
return CData_AtAddress(type, buf);
}
static char from_buffer_doc[] =
"C.from_buffer(object, offset=0) -> C instance\ncreate a C instance from a writeable buffer";
static int
KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep);
static PyObject *
CDataType_from_buffer(PyObject *type, PyObject *args)
{
void *buffer;
Py_ssize_t buffer_len;
Py_ssize_t offset = 0;
PyObject *obj, *result;
StgDictObject *dict = PyType_stgdict(type);
assert (dict);
if (!PyArg_ParseTuple(args,
#if (PY_VERSION_HEX < 0x02050000)
"O|i:from_buffer",
#else
"O|n:from_buffer",
#endif
&obj, &offset))
return NULL;
if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len))
return NULL;
if (offset < 0) {
PyErr_SetString(PyExc_ValueError,
"offset cannit be negative");
return NULL;
}
if (dict->size > buffer_len - offset) {
PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
"Buffer size too small (%d instead of at least %d bytes)",
#else
"Buffer size too small (%zd instead of at least %zd bytes)",
#endif
buffer_len, dict->size + offset);
return NULL;
}
result = CData_AtAddress(type, (char *)buffer + offset);
if (result == NULL)
return NULL;
Py_INCREF(obj);
if (-1 == KeepRef((CDataObject *)result, -1, obj)) {
Py_DECREF(result);
return NULL;
}
return result;
}
static char from_buffer_copy_doc[] =
"C.from_buffer_copy(object, offset=0) -> C instance\ncreate a C instance from a readable buffer";
static PyObject *
GenericCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static PyObject *
CDataType_from_buffer_copy(PyObject *type, PyObject *args)
{
void *buffer;
Py_ssize_t buffer_len;
Py_ssize_t offset = 0;
PyObject *obj, *result;
StgDictObject *dict = PyType_stgdict(type);
assert (dict);
if (!PyArg_ParseTuple(args,
#if (PY_VERSION_HEX < 0x02050000)
"O|i:from_buffer",
#else
"O|n:from_buffer",
#endif
&obj, &offset))
return NULL;
if (-1 == PyObject_AsReadBuffer(obj, &buffer, &buffer_len))
return NULL;
if (offset < 0) {
PyErr_SetString(PyExc_ValueError,
"offset cannit be negative");
return NULL;
}
if (dict->size > buffer_len - offset) {
PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
"Buffer size too small (%d instead of at least %d bytes)",
#else
"Buffer size too small (%zd instead of at least %zd bytes)",
#endif
buffer_len, dict->size + offset);
return NULL;
}
result = GenericCData_new((PyTypeObject *)type, NULL, NULL);
if (result == NULL)
return NULL;
memcpy(((CDataObject *)result)->b_ptr,
(char *)buffer+offset, dict->size);
return result;
}
static char in_dll_doc[] =
"C.in_dll(dll, name) -> C instance\naccess a C instance in a dll";
@ -513,6 +622,8 @@ CDataType_from_param(PyObject *type, PyObject *value)
static PyMethodDef CDataType_methods[] = {
{ "from_param", CDataType_from_param, METH_O, from_param_doc },
{ "from_address", CDataType_from_address, METH_O, from_address_doc },
{ "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
{ "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
{ "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc },
{ NULL, NULL },
};
@ -849,6 +960,8 @@ PointerType_from_param(PyObject *type, PyObject *value)
static PyMethodDef PointerType_methods[] = {
{ "from_address", CDataType_from_address, METH_O, from_address_doc },
{ "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
{ "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
{ "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
{ "from_param", (PyCFunction)PointerType_from_param, METH_O, from_param_doc},
{ "set_type", (PyCFunction)PointerType_set_type, METH_O },
@ -1920,6 +2033,8 @@ SimpleType_from_param(PyObject *type, PyObject *value)
static PyMethodDef SimpleType_methods[] = {
{ "from_param", SimpleType_from_param, METH_O, from_param_doc },
{ "from_address", CDataType_from_address, METH_O, from_address_doc },
{ "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
{ "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
{ "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
{ NULL, NULL },
};

View File

@ -202,7 +202,11 @@ int pysqlite_build_row_cast_map(pysqlite_Cursor* self)
decltype = sqlite3_column_decltype(self->statement->st, i);
if (decltype) {
for (pos = decltype;;pos++) {
if (*pos == ' ' || *pos == 0) {
/* Converter names are split at '(' and blanks.
* This allows 'INTEGER NOT NULL' to be treated as 'INTEGER' and
* 'NUMBER(10)' to be treated as 'NUMBER', for example.
* In other words, it will work as people expect it to work.*/
if (*pos == ' ' || *pos == '(' || *pos == 0) {
py_decltype = PyUnicode_FromStringAndSize(decltype, pos - decltype);
if (!py_decltype) {
return -1;

View File

@ -164,6 +164,30 @@ static PyObject* pysqlite_iter(pysqlite_Row* self)
return PyObject_GetIter(self->data);
}
static long pysqlite_row_hash(pysqlite_Row *self)
{
return PyObject_Hash(self->description) ^ PyObject_Hash(self->data);
}
static PyObject* pysqlite_row_richcompare(pysqlite_Row *self, PyObject *_other, int opid)
{
if (opid != Py_EQ && opid != Py_NE) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
if (PyType_IsSubtype(Py_TYPE(_other), &pysqlite_RowType)) {
pysqlite_Row *other = (pysqlite_Row *)_other;
PyObject *res = PyObject_RichCompare(self->description, other->description, opid);
if (opid == Py_EQ && res == Py_True
|| opid == Py_NE && res == Py_False) {
Py_DECREF(res);
return PyObject_RichCompare(self->data, other->data, opid);
}
}
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
PyMappingMethods pysqlite_row_as_mapping = {
/* mp_length */ (lenfunc)pysqlite_row_length,
/* mp_subscript */ (binaryfunc)pysqlite_row_subscript,
@ -191,7 +215,7 @@ PyTypeObject pysqlite_RowType = {
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(hashfunc)pysqlite_row_hash, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
@ -201,7 +225,7 @@ PyTypeObject pysqlite_RowType = {
0, /* tp_doc */
(traverseproc)0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
(richcmpfunc)pysqlite_row_richcompare, /* tp_richcompare */
0, /* tp_weaklistoffset */
(getiterfunc)pysqlite_iter, /* tp_iter */
0, /* tp_iternext */

View File

@ -89,10 +89,7 @@ int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* con
int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter, int allow_8bit_chars)
{
int rc = SQLITE_OK;
long longval;
#ifdef HAVE_LONG_LONG
PY_LONG_LONG longlongval;
#endif
const char* buffer;
char* string;
Py_ssize_t buflen;
@ -136,12 +133,8 @@ int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObjec
switch (paramtype) {
case TYPE_LONG:
/* in the overflow error case, longval/longlongval is -1, and an exception is set */
#ifdef HAVE_LONG_LONG
longlongval = PyLong_AsLongLong(parameter);
rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longlongval);
#else
rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval);
#endif
break;
case TYPE_FLOAT:
rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));

View File

@ -900,6 +900,24 @@ profile_int(PyObject *self, PyObject* args)
}
#endif
/* To test the format of tracebacks as printed out. */
static PyObject *
traceback_print(PyObject *self, PyObject *args)
{
PyObject *file;
PyObject *traceback;
int result;
if (!PyArg_ParseTuple(args, "OO:traceback_print",
&traceback, &file))
return NULL;
result = PyTraceBack_Print(traceback, file);
if (result < 0)
return NULL;
Py_RETURN_NONE;
}
static PyMethodDef TestMethods[] = {
{"raise_exception", raise_exception, METH_VARARGS},
{"test_config", (PyCFunction)test_config, METH_NOARGS},
@ -942,6 +960,7 @@ static PyMethodDef TestMethods[] = {
#ifdef HAVE_GETTIMEOFDAY
{"profile_int", profile_int, METH_NOARGS},
#endif
{"traceback_print", traceback_print, METH_VARARGS},
{NULL, NULL} /* sentinel */
};

View File

@ -653,6 +653,7 @@ math_pow(PyObject *self, PyObject *args)
/* deal directly with IEEE specials, to cope with problems on various
platforms whose semantics don't exactly match C99 */
r = 0.; /* silence compiler warning */
if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
errno = 0;
if (Py_IS_NAN(x))

View File

@ -133,6 +133,7 @@ char meta_name[80]; /* package name without version like
char install_script[MAX_PATH];
char *pre_install_script; /* run before we install a single file */
char user_access_control[10]; // one of 'auto', 'force', otherwise none.
int py_major, py_minor; /* Python version selected for installation */
@ -344,8 +345,15 @@ struct PyMethodDef {
};
typedef struct PyMethodDef PyMethodDef;
// XXX - all of these are potentially fragile! We load and unload
// the Python DLL multiple times - so storing functions pointers
// is dangerous (although things *look* OK at present)
// Better might be to roll prepare_script_environment() into
// LoadPythonDll(), and create a new UnloadPythonDLL() which also
// clears the global pointers.
void *(*g_Py_BuildValue)(char *, ...);
int (*g_PyArg_ParseTuple)(PyObject *, char *, ...);
PyObject * (*g_PyLong_FromVoidPtr)(void *);
PyObject *g_PyExc_ValueError;
PyObject *g_PyExc_OSError;
@ -597,7 +605,7 @@ static PyObject *PyMessageBox(PyObject *self, PyObject *args)
static PyObject *GetRootHKey(PyObject *self)
{
return g_Py_BuildValue("l", hkey_root);
return g_PyLong_FromVoidPtr(hkey_root);
}
#define METH_VARARGS 0x0001
@ -631,7 +639,9 @@ static HINSTANCE LoadPythonDll(char *fname)
"SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath",
py_major, py_minor);
if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name,
fullpath, &size))
fullpath, &size) &&
ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name,
fullpath, &size))
return NULL;
strcat(fullpath, "\\");
strcat(fullpath, fname);
@ -648,6 +658,7 @@ static int prepare_script_environment(HINSTANCE hPython)
DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *));
if (!PyImport_ImportModule || !PyObject_GetAttrString ||
!PyObject_SetAttrString || !PyCFunction_New)
return 1;
@ -667,6 +678,7 @@ static int prepare_script_environment(HINSTANCE hPython)
g_Py_BuildValue = Py_BuildValue;
g_PyArg_ParseTuple = PyArg_ParseTuple;
g_PyErr_Format = PyErr_Format;
g_PyLong_FromVoidPtr = PyLong_FromVoidPtr;
return 0;
}
@ -777,7 +789,9 @@ static int run_simple_script(char *script)
hPython = LoadPythonDll(pythondll);
if (!hPython) {
set_failure_reason("Can't load Python for pre-install script");
char reason[128];
wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError());
set_failure_reason(reason);
return -1;
}
rc = do_run_simple_script(hPython, script);
@ -2073,6 +2087,71 @@ void RunWizard(HWND hwnd)
PropertySheet(&psh);
}
// subtly different from HasLocalMachinePrivs(), in that after executing
// an 'elevated' process, we expect this to return TRUE - but there is no
// such implication for HasLocalMachinePrivs
BOOL MyIsUserAnAdmin()
{
typedef BOOL (WINAPI *PFNIsUserAnAdmin)();
static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL;
HMODULE shell32;
// This function isn't guaranteed to be available (and it can't hurt
// to leave the library loaded)
if (0 == (shell32=LoadLibrary("shell32.dll")))
return FALSE;
if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin")))
return FALSE;
return (*pfnIsUserAnAdmin)();
}
// Some magic for Vista's UAC. If there is a target_version, and
// if that target version is installed in the registry under
// HKLM, and we are not current administrator, then
// re-execute ourselves requesting elevation.
// Split into 2 functions - "should we elevate" and "spawn elevated"
// Returns TRUE if we should spawn an elevated child
BOOL NeedAutoUAC()
{
HKEY hk;
char key_name[80];
OSVERSIONINFO winverinfo;
winverinfo.dwOSVersionInfoSize = sizeof(winverinfo);
// If less than XP, then we can't do it (and its not necessary).
if (!GetVersionEx(&winverinfo) || winverinfo.dwMajorVersion < 5)
return FALSE;
// no Python version info == we can't know yet.
if (target_version[0] == '\0')
return FALSE;
// see how python is current installed
wsprintf(key_name,
"Software\\Python\\PythonCore\\%s\\InstallPath",
target_version);
if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE,
key_name, 0, KEY_READ, &hk))
return FALSE;
RegCloseKey(hk);
// Python is installed in HKLM - we must elevate.
return TRUE;
}
// Spawn ourself as an elevated application. On failure, a message is
// displayed to the user - but this app will always terminate, even
// on error.
void SpawnUAC()
{
// interesting failure scenario that has been seen: initial executable
// runs from a network drive - but once elevated, that network share
// isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED.
int ret = (int)ShellExecute(0, "runas", modulename, "", NULL,
SW_SHOWNORMAL);
if (ret <= 32) {
char msg[128];
wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret);
MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR);
}
}
int DoInstall(void)
{
char ini_buffer[4096];
@ -2106,6 +2185,31 @@ int DoInstall(void)
install_script, sizeof(install_script),
ini_file);
GetPrivateProfileString("Setup", "user_access_control", "",
user_access_control, sizeof(user_access_control), ini_file);
// See if we need to do the Vista UAC magic.
if (strcmp(user_access_control, "force")==0) {
if (!MyIsUserAnAdmin()) {
SpawnUAC();
return 0;
}
// already admin - keep going
} else if (strcmp(user_access_control, "auto")==0) {
// Check if it looks like we need UAC control, based
// on how Python itself was installed.
if (!MyIsUserAnAdmin() && NeedAutoUAC()) {
SpawnUAC();
return 0;
}
} else {
// display a warning about unknown values - only the developer
// of the extension will see it (until they fix it!)
if (user_access_control[0] && strcmp(user_access_control, "none") != 0) {
MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK);
// nothing to do.
}
}
hwndMain = CreateBackground(title);

View File

@ -24,7 +24,7 @@
Name="VCCLCompilerTool"
Optimization="1"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\Include,..\..\..\zlib-1.2.1"
AdditionalIncludeDirectories="..\..\Include,..\..\..\zlib-1.2.3"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
StringPooling="TRUE"
RuntimeLibrary="2"
@ -41,7 +41,7 @@
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="..\..\..\zlib-1.2.1\zlib.lib imagehlp.lib comctl32.lib"
AdditionalDependencies="..\..\..\zlib-1.2.3\zlib.lib imagehlp.lib comctl32.lib"
OutputFile="..\..\lib\distutils\command/wininst-7.1.exe"
LinkIncremental="1"
SuppressStartupBanner="TRUE"

View File

@ -43,7 +43,7 @@ RSC=rc.exe
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /MD /W3 /O1 /I "..\..\Include" /I "..\..\..\zlib-1.2.1" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
# ADD CPP /nologo /MD /W3 /O1 /I "..\..\Include" /I "..\..\..\zlib-1.2.3" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x407 /d "NDEBUG"
@ -53,7 +53,7 @@ BSC32=bscmake.exe
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
# ADD LINK32 ..\..\..\zlib-1.2.1\zlib.lib imagehlp.lib comdlg32.lib ole32.lib comctl32.lib kernel32.lib user32.lib gdi32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"LIBC" /out:"..\..\lib\distutils\command/wininst-6.exe"
# ADD LINK32 ..\..\..\zlib-1.2.3\zlib.lib imagehlp.lib comdlg32.lib ole32.lib comctl32.lib kernel32.lib user32.lib gdi32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"LIBC" /out:"..\..\lib\distutils\command/wininst-6.0.exe"
!ELSEIF "$(CFG)" == "wininst - Win32 Debug"
@ -79,7 +79,7 @@ BSC32=bscmake.exe
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
# ADD LINK32 ..\..\..\zlib-1.2.1\zlib.lib imagehlp.lib comdlg32.lib ole32.lib comctl32.lib kernel32.lib user32.lib gdi32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /pdb:none /debug /machine:I386 /nodefaultlib:"LIBC" /out:"..\..\lib\distutils\command/wininst-6_d.exe"
# ADD LINK32 ..\..\..\zlib-1.2.3\zlib.lib imagehlp.lib comdlg32.lib ole32.lib comctl32.lib kernel32.lib user32.lib gdi32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /pdb:none /debug /machine:I386 /nodefaultlib:"LIBC" /out:"..\..\lib\distutils\command/wininst-6.0_d.exe"
!ENDIF

View File

@ -1371,7 +1371,7 @@ tok_get(register struct tok_state *tok, char **p_start, char **p_end)
else if (c == 'o' || c == 'O') {
/* Octal */
c = tok_nextc(tok);
if (c < '0' || c > '8') {
if (c < '0' || c >= '8') {
tok->done = E_TOKEN;
tok_backup(tok, c);
return ERRORTOKEN;

Some files were not shown because too many files have changed in this diff Show More