Port rev. 56940, 56943.

This commit is contained in:
Georg Brandl 2007-08-12 08:03:59 +00:00
parent bbf900dd4a
commit bc0ec2c4ae
11 changed files with 66 additions and 145 deletions

View File

@ -108,7 +108,7 @@ setup script). Indirectly provides the :class:`distutils.dist.Distribution` and
args from *script* to :func:`setup`), or the contents of the config files or
command-line.
*script_name* is a file that will be run with :func:`execfile` ``sys.argv[0]``
*script_name* is a file that will be read and run with :func:`exec`. ``sys.argv[0]``
will be replaced with *script* for the duration of the call. *script_args* is a
list of strings; if supplied, ``sys.argv[1:]`` will be replaced by *script_args*
for the duration of the call.

View File

@ -75,8 +75,8 @@ There are situations in which ``from module import *`` is just fine:
* When the module advertises itself as ``from import *`` safe.
Unadorned :keyword:`exec`, :func:`execfile` and friends
-------------------------------------------------------
Unadorned :keyword:`exec` and friends
-------------------------------------
The word "unadorned" refers to the use without an explicit dictionary, in which
case those constructs evaluate code in the *current* environment. This is
@ -91,7 +91,7 @@ Bad examples::
>>> def func(s, **kw):
>>> for var, val in kw.items():
>>> exec "s.%s=val" % var # invalid!
>>> execfile("handler.py")
>>> exec(open("handler.py").read())
>>> handle()
Good examples::
@ -103,7 +103,7 @@ Good examples::
>>> for var, val in kw.items():
>>> setattr(s, var, val)
>>> d={}
>>> execfile("handle.py", d, d)
>>> exec(open("handle.py").read(), d, d)
>>> handle = d['handle']
>>> handle()

View File

@ -1709,7 +1709,7 @@ code under the debugger:
it does, then post-mortem debugging is invoked, via :func:`pdb.post_mortem`,
passing the traceback object from the unhandled exception. If *pm* is not
specified, or is false, the script is run under the debugger from the start, via
passing an appropriate :func:`execfile` call to :func:`pdb.run`.
passing an appropriate :func:`exec` call to :func:`pdb.run`.
.. versionadded:: 2.3

View File

@ -286,9 +286,9 @@ The following exceptions are the exceptions that are actually raised.
.. exception:: SyntaxError
Raised when the parser encounters a syntax error. This may occur in an
:keyword:`import` statement, in a call to the built-in functions :func:`exec`,
:func:`execfile`, :func:`eval` or :func:`input`, or when reading the initial
script or standard input (also interactively).
:keyword:`import` statement, in a call to the built-in functions :func:`exec`
or :func:`eval`, or when reading the initial script or standard input
(also interactively).
.. % XXXJH xref to these functions?

View File

@ -106,10 +106,10 @@ available. They are listed here in alphabetical order.
.. function:: basestring()
This abstract type is the superclass for :class:`str` and :class:`unicode`. It
This abstract type is the superclass for :class:`str`. It
cannot be called or instantiated, but it can be used to test whether an object
is an instance of :class:`str` or :class:`unicode`. ``isinstance(obj,
basestring)`` is equivalent to ``isinstance(obj, (str, unicode))``.
is an instance of :class:`str` (or a user-defined type inherited from
:class:`basestring`).
.. versionadded:: 2.3
@ -141,11 +141,11 @@ available. They are listed here in alphabetical order.
.. function:: chr(i)
Return a string of one character whose ASCII code is the integer *i*. For
Return the string of one character whose Unicode codepoint is the integer *i*. For
example, ``chr(97)`` returns the string ``'a'``. This is the inverse of
:func:`ord`. The argument must be in the range [0..255], inclusive;
:exc:`ValueError` will be raised if *i* is outside that range. See
also :func:`unichr`.
:func:`ord`. The valid range for the argument depends how Python was
configured -- it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF].
:exc:`ValueError` will be raised if *i* is outside that range.
.. function:: classmethod(function)
@ -368,10 +368,9 @@ available. They are listed here in alphabetical order.
*kind* argument.
Hints: dynamic execution of statements is supported by the :func:`exec`
function. Execution of statements from a file is supported by the
:func:`execfile` function. The :func:`globals` and :func:`locals` functions
function. The :func:`globals` and :func:`locals` functions
returns the current global and local dictionary, respectively, which may be
useful to pass around for use by :func:`eval` or :func:`execfile`.
useful to pass around for use by :func:`eval` or :func:`exec`.
.. function:: exec(object[, globals[, locals]])
@ -405,48 +404,15 @@ available. They are listed here in alphabetical order.
global and local dictionary, respectively, which may be useful to pass around
for use as the second and third argument to :func:`exec`.
.. function:: execfile(filename[, globals[, locals]])
This function is similar to the :func:`exec` function, but parses a file given
by the file name instead of a string. It is different from the
:keyword:`import` statement in that it does not use the module administration
--- it reads the file unconditionally and does not create a new module.
The arguments are a file name and two optional dictionaries. The file is parsed
and evaluated as a sequence of Python statements (similarly to a module) using
the *globals* and *locals* dictionaries as global and local namespace. If
provided, *locals* can be any mapping object.
.. versionchanged:: 2.4
formerly *locals* was required to be a dictionary.
If the *locals* dictionary is omitted it defaults to the *globals* dictionary.
If both dictionaries are omitted, the expression is executed in the environment
where :func:`execfile` is called. The return value is ``None``.
.. warning::
The default *locals* act as described for function :func:`locals` below:
modifications to the default *locals* dictionary should not be attempted. Pass
an explicit *locals* dictionary if you need to see effects of the code on
*locals* after function :func:`execfile` returns. :func:`execfile` cannot be
*locals* after function :func:`execfile` returns. :func:`exec` cannot be
used reliably to modify a function's locals.
.. function:: file(filename[, mode[, bufsize]])
Constructor function for the :class:`file` type, described further in section
:ref:`bltin-file-objects`. The constructor's arguments are the same as those
of the :func:`open` built-in function described below.
When opening a file, it's preferable to use :func:`open` instead of invoking
this constructor directly. :class:`file` is more suited to type testing (for
example, writing ``isinstance(f, file)``).
.. versionadded:: 2.2
.. function:: filter(function, iterable)
Construct a list from those elements of *iterable* for which *function* returns
@ -559,15 +525,15 @@ available. They are listed here in alphabetical order.
.. function:: int([x[, radix]])
Convert a string or number to a plain integer. If the argument is a string, it
must contain a possibly signed decimal number representable as a Python integer,
possibly embedded in whitespace. The *radix* parameter gives the base for the
Convert a string or number to an integer. If the argument is a string, it
must contain a possibly signed number of arbitrary size,
possibly embedded in whitespace. The *radix* parameter gives the base for the
conversion and may be any integer in the range [2, 36], or zero. If *radix* is
zero, the interpretation is the same as for integer literals. If *radix* is
specified and *x* is not a string, :exc:`TypeError` is raised. Otherwise, the
argument may be a plain or long integer or a floating point number. Conversion
of floating point numbers to integers truncates (towards zero). If the argument
is outside the integer range a long object will be returned instead. If no
specified and *x* is not a string, :exc:`TypeError` is raised. Otherwise, the
argument may be another integer, a floating point number or any other object
that has an :meth:`__int__` method. Conversion
of floating point numbers to integers truncates (towards zero). If no
arguments are given, returns ``0``.
The integer type is described in :ref:`typesnumeric`.
@ -650,18 +616,6 @@ available. They are listed here in alphabetical order.
interpreter. Free variables are not returned in class blocks.
.. function:: long([x[, radix]])
Convert a string or number to a long integer. If the argument is a string, it
must contain a possibly signed number of arbitrary size, possibly embedded in
whitespace. The *radix* argument is interpreted in the same way as for
:func:`int`, and may only be given when *x* is a string. Otherwise, the argument
may be a plain or long integer or a floating point number, and a long integer
with the same value is returned. Conversion of floating point numbers to
integers truncates (towards zero). If no arguments are given, returns ``0L``.
The long type is described in :ref:`typesnumeric`.
.. function:: map(function, iterable, ...)
Apply *function* to every item of *iterable* and return a list of the results.
@ -1009,13 +963,30 @@ available. They are listed here in alphabetical order.
Function decorator syntax added.
.. function:: str([object])
.. function:: str([object[, encoding[, errors]]])
Return a string containing a nicely printable representation of an object. For
strings, this returns the string itself. The difference with ``repr(object)``
Return a string version of an object, using one of the following modes:
If *encoding* and/or *errors* are given, :func:`str` will decode the
*object* which can either be a byte string or a character buffer using
the codec for *encoding*. The *encoding* parameter is a string giving
the name of an encoding; if the encoding is not known, :exc:`LookupError`
is raised. Error handling is done according to *errors*; this specifies the
treatment of characters which are invalid in the input encoding. If
*errors* is ``'strict'`` (the default), a :exc:`ValueError` is raised on
errors, while a value of ``'ignore'`` causes errors to be silently ignored,
and a value of ``'replace'`` causes the official Unicode replacement character,
U+FFFD, to be used to replace input characters which cannot be decoded.
See also the :mod:`codecs` module.
When only *object* is given, this returns its nicely printable representation.
For strings, this is the string itself. The difference with ``repr(object)``
is that ``str(object)`` does not always attempt to return a string that is
acceptable to :func:`eval`; its goal is to return a printable string. If no
argument is given, returns the empty string, ``''``.
acceptable to :func:`eval`; its goal is to return a printable string.
With no arguments, this returns the empty string.
Objects can specify what ``str(object)`` returns by defining a :meth:`__str__`
special method.
For more information on strings see :ref:`typesseq` which describes sequence
functionality (strings are sequences), and also the string-specific methods
@ -1101,56 +1072,6 @@ available. They are listed here in alphabetical order.
.. versionadded:: 2.2
.. function:: unichr(i)
Return the Unicode string of one character whose Unicode code is the integer
*i*. For example, ``unichr(97)`` returns the string ``u'a'``. This is the
inverse of :func:`ord` for Unicode strings. The valid range for the argument
depends how Python was configured -- it may be either UCS2 [0..0xFFFF] or UCS4
[0..0x10FFFF]. :exc:`ValueError` is raised otherwise. For ASCII and 8-bit
strings see :func:`chr`.
.. versionadded:: 2.0
.. function:: unicode([object[, encoding [, errors]]])
Return the Unicode string version of *object* using one of the following modes:
If *encoding* and/or *errors* are given, ``unicode()`` will decode the object
which can either be an 8-bit string or a character buffer using the codec for
*encoding*. The *encoding* parameter is a string giving the name of an encoding;
if the encoding is not known, :exc:`LookupError` is raised. Error handling is
done according to *errors*; this specifies the treatment of characters which are
invalid in the input encoding. If *errors* is ``'strict'`` (the default), a
:exc:`ValueError` is raised on errors, while a value of ``'ignore'`` causes
errors to be silently ignored, and a value of ``'replace'`` causes the official
Unicode replacement character, ``U+FFFD``, to be used to replace input
characters which cannot be decoded. See also the :mod:`codecs` module.
If no optional parameters are given, ``unicode()`` will mimic the behaviour of
``str()`` except that it returns Unicode strings instead of 8-bit strings. More
precisely, if *object* is a Unicode string or subclass it will return that
Unicode string without any additional decoding applied.
For objects which provide a :meth:`__unicode__` method, it will call this method
without arguments to create a Unicode string. For all other objects, the 8-bit
string version or representation is requested and then converted to a Unicode
string using the codec for the default encoding in ``'strict'`` mode.
For more information on Unicode strings see :ref:`typesseq` which describes
sequence functionality (Unicode strings are sequences), and also the
string-specific methods described in the :ref:`string-methods` section. To
output formatted strings use template strings or the ``%`` operator described
in the :ref:`string-formatting` section. In addition see the
:ref:`stringservices` section. See also :func:`str`.
.. versionadded:: 2.0
.. versionchanged:: 2.2
Support for :meth:`__unicode__` added.
.. function:: vars([object])
Without arguments, return a dictionary corresponding to the current local symbol
@ -1201,6 +1122,8 @@ bypass these functions without concerns about missing something important.
extend to the end of *object* (or will have a length given by the *size*
argument).
.. rubric:: Footnotes
.. [#] Specifying a buffer size currently has no effect on systems that don't have

View File

@ -21,10 +21,10 @@ must execute the statement ::
import user
.. index:: builtin: execfile
.. index:: builtin: exec
The :mod:`user` module looks for a file :file:`.pythonrc.py` in the user's home
directory and if it can be opened, executes it (using :func:`execfile`) in its
directory and if it can be opened, executes it (using :func:`exec`) in its
own (the module :mod:`user`'s) global namespace. Errors during this phase are
not caught; that's up to the program that imports the :mod:`user` module, if it
wishes. The home directory is assumed to be named by the :envvar:`HOME`

View File

@ -33,8 +33,7 @@ The following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block. A script file (a file given as
standard input to the interpreter or specified on the interpreter command line
the first argument) is a code block. A script command (a command specified on
the interpreter command line with the '**-c**' option) is a code block. The
file read by the built-in function :func:`execfile` is a code block. The string
the interpreter command line with the '**-c**' option) is a code block. The string
argument passed to the built-in functions :func:`eval` and :func:`exec` is a
code block. The expression read and evaluated by the built-in function
:func:`input` is a code block.
@ -158,11 +157,11 @@ If the wild card form of import --- ``import *`` --- is used in a function and
the function contains or is a nested block with free variables, the compiler
will raise a :exc:`SyntaxError`.
The :func:`eval`, :func:`exec`, :func:`execfile`, and :func:`input` functions do
The :func:`eval` and :func:`exec` functions do
not have access to the full environment for resolving names. Names may be
resolved in the local and global namespaces of the caller. Free variables are
not resolved in the nearest enclosing namespace, but in the global namespace.
[#]_ The :func:`exec`, :func:`eval` and :func:`execfile` functions have optional
[#]_ The :func:`exec` and :func:`eval` functions have optional
arguments to override the global and local namespace. If only one namespace is
specified, it is used for both.

View File

@ -761,8 +761,8 @@ Note that there is nothing special about the statement::
That is not a future statement; it's an ordinary import statement with no
special semantics or syntax restrictions.
Code compiled by calls to the builtin functions :func:`exec`, :func:`compile`
and :func:`execfile` that occur in a module :mod:`M` containing a future
Code compiled by calls to the builtin functions :func:`exec` and :func:`compile`
that occur in a module :mod:`M` containing a future
statement will, by default, use the new syntax or semantics associated with the
future statement. This can, starting with Python 2.2 be controlled by optional
arguments to :func:`compile` --- see the documentation of that function
@ -807,7 +807,6 @@ them or silently change the meaning of the program.)
.. index::
builtin: exec
builtin: eval
builtin: execfile
builtin: compile
**Programmer's note:** the :keyword:`global` is a directive to the parser. It
@ -816,8 +815,7 @@ In particular, a :keyword:`global` statement contained in a string or code
object supplied to the builtin :func:`exec` function does not affect the code
block *containing* the function call, and code contained in such a string is
unaffected by :keyword:`global` statements in the code containing the function
call. The same applies to the :func:`eval`, :func:`execfile` and
:func:`compile` functions.
call. The same applies to the :func:`eval` and :func:`compile` functions.
.. rubric:: Footnotes

View File

@ -541,7 +541,7 @@ as in the debugger, and that's one reason why this loophole is not closed.
(Buglet: derivation of a class with the same name as the base class makes use of
private variables of the base class possible.)
Notice that code passed to ``exec()``, ``eval()`` or ``execfile()`` does not
Notice that code passed to ``exec()`` or ``eval()`` does not
consider the classname of the invoking class to be the current class; this is
similar to the effect of the ``global`` statement, the effect of which is
likewise restricted to code that is byte-compiled together. The same

View File

@ -232,13 +232,14 @@ file.
If you want to read an additional start-up file from the current directory, you
can program this in the global start-up file using code like ``if
os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')``. If you want to use
the startup file in a script, you must do this explicitly in the script::
os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``.
If you want to use the startup file in a script, you must do this explicitly
in the script::
import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
execfile(filename)
exec(open(filename).read())
.. rubric:: Footnotes

View File

@ -324,14 +324,14 @@ want a list of those, they are defined in the standard module
'__name__', 'abs', 'basestring', 'bool', 'buffer',
'chr', 'classmethod', 'cmp', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'enumerate', 'eval', 'exec', 'exit', 'filter', 'float',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
'len', 'license', 'list', 'locals', 'map', 'max', 'min',
'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
'repr', 'reversed', 'round', 'set',
'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
'tuple', 'type', 'unichr', 'unicode', 'vars', 'zip']
'tuple', 'type', 'vars', 'zip']
.. _tut-packages: