Patch #1550800: make exec a function.

This commit is contained in:
Georg Brandl 2006-09-06 06:51:57 +00:00
parent 4e472e05bd
commit 7cae87ca7b
105 changed files with 1246 additions and 1583 deletions

View File

@ -123,16 +123,6 @@ class Unparser:
self.write(", ")
self.dispatch(t.msg)
def _Exec(self, t):
self.fill("exec ")
self.dispatch(t.body)
if t.globals:
self.write(" in ")
self.dispatch(t.globals)
if t.locals:
self.write(", ")
self.dispatch(t.locals)
def _Print(self, t):
self.fill("print ")
do_comma = False

View File

@ -108,7 +108,7 @@ def run_command(code, stdin, stdout, globals):
sys.stdout = sys.stderr = stdout
sys.stdin = stdin
try:
exec code in globals
exec(code, globals)
except SystemExit, how:
raise SystemExit, how, sys.exc_info()[2]
except:

View File

@ -40,7 +40,7 @@ def execute(request):
sys.stdout = sys.stderr = fakefile = StringIO.StringIO()
try:
try:
exec request in {}, {}
exec(request, {}, {})
except:
print
traceback.print_exc(100)

View File

@ -81,7 +81,7 @@ There are situations in which \code{from module import *} is just fine:
\end{itemize}
\subsection{Unadorned \keyword{exec}, \function{execfile} and friends}
\subsection{Unadorned \function{exec}, \function{execfile} and friends}
The word ``unadorned'' refers to the use without an explicit dictionary,
in which case those constructs evaluate code in the {\em current} environment.
@ -93,10 +93,10 @@ Bad examples:
\begin{verbatim}
>>> for name in sys.argv[1:]:
>>> exec "%s=1" % name
>>> exec("%s=1" % name)
>>> def func(s, **kw):
>>> for var, val in kw.items():
>>> exec "s.%s=val" % var # invalid!
>>> exec("s.%s=val" % var) # invalid!
>>> execfile("handler.py")
>>> handle()
\end{verbatim}

View File

@ -408,11 +408,6 @@ to the local namespace. The module is popped after loading all names.
This opcode implements \code{from module import *}.
\end{opcodedesc}
\begin{opcodedesc}{EXEC_STMT}{}
Implements \code{exec TOS2,TOS1,TOS}. The compiler fills
missing optional parameters with \code{None}.
\end{opcodedesc}
\begin{opcodedesc}{POP_BLOCK}{}
Removes one block from the block stack. Per frame, there is a
stack of blocks, denoting nested loops, try statements, and such.

View File

@ -293,10 +293,10 @@ Raised when an \keyword{assert} statement fails.
\begin{excdesc}{SyntaxError}
% XXXJH xref to these functions?
Raised when the parser encounters a syntax error. This may occur in
an \keyword{import} statement, in an \keyword{exec} statement, in a call
to the built-in function \function{eval()} or \function{input()}, or
when reading the initial script or standard input (also
interactively).
an \keyword{import} statement, in a call to the built-in functions
\function{exec()}, \function{execfile()}, \function{eval()} or
\function{input()}, or when reading the initial script or standard
input (also interactively).
Instances of this class have attributes \member{filename},
\member{lineno}, \member{offset} and \member{text} for easier access

View File

@ -178,7 +178,7 @@ class C:
\begin{funcdesc}{compile}{string, filename, kind\optional{,
flags\optional{, dont_inherit}}}
Compile the \var{string} into a code object. Code objects can be
executed by an \keyword{exec} statement or evaluated by a call to
executed by a call to \function{exec()} or evaluated by a call to
\function{eval()}. The \var{filename} argument should
give the file from which the code was read; pass some recognizable value
if it wasn't read from a file (\code{'<string>'} is commonly used).
@ -366,7 +366,7 @@ class C:
compiled passing \code{'eval'} as the \var{kind} argument.
Hints: dynamic execution of statements is supported by the
\keyword{exec} statement. Execution of statements from a file is
\function{exec()} function. Execution of statements from a file is
supported by the \function{execfile()} function. The
\function{globals()} and \function{locals()} functions returns the
current global and local dictionary, respectively, which may be
@ -374,13 +374,47 @@ class C:
\function{execfile()}.
\end{funcdesc}
\begin{funcdesc}{exec}{object\optional{, globals\optional{, locals}}}
This function supports dynamic execution of Python code.
\var{object} must be either a string, an open file object, or
a code object. If it is a string, the string is parsed as a suite of
Python statements which is then executed (unless a syntax error
occurs). If it is an open file, the file is parsed until \EOF{} and
executed. If it is a code object, it is simply executed. In all
cases, the code that's executed is expected to be valid as file
input (see the section ``File input'' in the Reference Manual).
Be aware that the \keyword{return} and \keyword{yield} statements may
not be used outside of function definitions even within the context of
code passed to the \function{exec()} function.
The return value is \code{None}.
In all cases, if the optional parts are omitted, the code is executed
in the current scope. If only \var{globals} is provided, it must be
a dictionary, which will be used for both the global and the local
variables. If \var{globals} and \var{locals} are given, they are used
for the global and local variables, respectively. If provided,
\var{locals} can be any mapping object.
If the \var{globals} dictionary does not contain a value for the
key \code{__builtins__}, a reference to the dictionary of the built-in
module \module{__builtin__} is inserted under that key. That way you
can control what builtins are available to the executed code by
inserting your own \code{__builtins__} dictionary into \var{globals}
before passing it to \function{exec()}.
\note{The built-in functions \function{globals()} and \function{locals()}
return the current global and local dictionary, respectively, which
may be useful to pass around for use as the second and third
argument to \function{exec()}.}
\end{funcdesc}
\begin{funcdesc}{execfile}{filename\optional{, globals\optional{, locals}}}
This function is similar to the
\keyword{exec} statement, but parses a file instead of a string. It
This function is similar to the \function{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.\footnote{It is used relatively
rarely so does not warrant being made into a statement.}
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

View File

@ -61,7 +61,7 @@ Return the file descriptor of the profiler's log file.
\end{methoddesc}
\begin{methoddesc}{run}{cmd}
Profile an \keyword{exec}-compatible string in the script environment.
Profile an \function{exec()}-compatible string in the script environment.
The globals from the \refmodule[main]{__main__} module are used as
both the globals and locals for the script.
\end{methoddesc}
@ -76,7 +76,7 @@ disabled on the way out.
\begin{methoddesc}{runctx}{cmd, globals, locals}
Evaluate an \keyword{exec}-compatible string in a specific environment.
Profile an \function{exec()}-compatible string in a specific environment.
The string is compiled before profiling begins.
\end{methoddesc}

View File

@ -193,8 +193,9 @@ false or omitted.
\begin{funcdesc}{compileast}{ast\optional{, filename\code{ = '<ast>'}}}
The Python byte compiler can be invoked on an AST object to produce
code objects which can be used as part of an \keyword{exec} statement or
a call to the built-in \function{eval()}\bifuncindex{eval} function.
code objects which can be used as part of a call to the built-in
\function{exec()}\bifuncindex{exec} or \function{eval()}
\bifuncindex{eval} functions.
This function provides the interface to the compiler, passing the
internal parse tree from \var{ast} to the parser, using the
source file name specified by the \var{filename} parameter.

View File

@ -79,8 +79,8 @@ the statement using \samp{step} or \samp{next} (all these commands are
explained below). The optional \var{globals} and \var{locals}
arguments specify the environment in which the code is executed; by
default the dictionary of the module \refmodule[main]{__main__} is
used. (See the explanation of the \keyword{exec} statement or the
\function{eval()} built-in function.)
used. (See the explanation of the built-in \function{exec()} or
\function{eval()} functions.)
\end{funcdesc}
\begin{funcdesc}{runeval}{expression\optional{, globals\optional{, locals}}}

View File

@ -319,9 +319,9 @@ code for these modules.
\begin{funcdesc}{run}{command\optional{, filename}}
This function takes a single argument that has can be passed to the
\keyword{exec} statement, and an optional file name. In all cases this
routine attempts to \keyword{exec} its first argument, and gather profiling
This function takes a single argument that can be passed to the
\function{exec()} function, and an optional file name. In all cases this
routine attempts to \function{exec()} its first argument, and gather profiling
statistics from the execution. If no file name is present, then this
function automatically prints a simple profiling report, sorted by the
standard name string (file/line/function-name) that is presented in

View File

@ -11,10 +11,10 @@
\end{notice}
This module contains the \class{RExec} class, which supports
\method{r_eval()}, \method{r_execfile()}, \method{r_exec()}, and
\method{r_exec()}, \method{r_eval()}, \method{r_execfile()}, and
\method{r_import()} methods, which are restricted versions of the standard
Python functions \method{eval()}, \method{execfile()} and
the \keyword{exec} and \keyword{import} statements.
Python functions \method{exec()}, \method{eval()}, \method{execfile()} and
the \keyword{import} statement.
Code executed in this restricted environment will
only have access to modules and functions that are deemed safe; you
can subclass \class{RExec} to add or remove capabilities as desired.

View File

@ -1972,9 +1972,9 @@ attribute.
\withsubitem{(function object attribute)}{\ttindex{func_code}}
A code object can be executed or evaluated by passing it (instead of a
source string) to the \keyword{exec} statement or the built-in
\function{eval()} function.
\stindex{exec}
source string) to the \function{exec()} or \function{eval()}
built-in functions.
\bifuncindex{exec}
\bifuncindex{eval}
See the \citetitle[../ref/ref.html]{Python Reference Manual} for more

View File

@ -139,7 +139,7 @@ import sys, traceback
def run_user_code(envdir):
source = raw_input(">>> ")
try:
exec source in envdir
exec(source, envdir)
except:
print "Exception in user code:"
print '-'*60

View File

@ -308,13 +308,12 @@ identifiers. They must be spelled exactly as written here:%
\index{reserved word}
\begin{verbatim}
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
and def for is raise
as del from lambda return
assert elif global not try
break else if or while
class except import pass with
continue finally in print yield
\end{verbatim}
% When adding keywords, use reswords.py for reformatting

View File

@ -20,8 +20,8 @@ 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 `\strong{-c}' option) is a code
block. The file read by the built-in function \function{execfile()}
is a code block. The string argument passed to the built-in function
\function{eval()} and to the \keyword{exec} statement is a code block.
is a code block. The string argument passed to the built-in functions
\function{eval()} and \function{exec()} is a code block.
The expression read and evaluated by the built-in function
\function{input()} is a code block.
@ -139,22 +139,16 @@ If the wild card form of import --- \samp{import *} --- is used in a
function and the function contains or is a nested block with free
variables, the compiler will raise a \exception{SyntaxError}.
If \keyword{exec} is used in a function and the function contains or
is a nested block with free variables, the compiler will raise a
\exception{SyntaxError} unless the exec explicitly specifies the local
namespace for the \keyword{exec}. (In other words, \samp{exec obj}
would be illegal, but \samp{exec obj in ns} would be legal.)
The \function{eval()}, \function{execfile()}, and \function{input()}
functions and the \keyword{exec} statement do not have access to the
The \function{eval()}, \function{exec()}, \function{execfile()},
and \function{input()} 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.\footnote{This limitation occurs because the code that is
executed by these operations is not available at the time the
module is compiled.}
The \keyword{exec} statement and the \function{eval()} and
\function{execfile()} functions have optional arguments to override
The \function{exec()}, \function{eval()} and \function{execfile()}
functions have optional arguments to override
the global and local namespace. If only one namespace is specified,
it is used for both.

View File

@ -20,7 +20,6 @@ by semicolons. The syntax for simple statements is:
\productioncont{| \token{continue_stmt}}
\productioncont{| \token{import_stmt}}
\productioncont{| \token{global_stmt}}
\productioncont{| \token{exec_stmt}}
\end{productionlist}
@ -809,7 +808,7 @@ import __future__ [as name]
That is not a future statement; it's an ordinary import statement with
no special semantics or syntax restrictions.
Code compiled by an \keyword{exec} statement or calls to the builtin functions
Code compiled by calls to the builtin functions \function{exec()},
\function{compile()} and \function{execfile()} that occur in a module
\module{M} containing a future statement will, by default, use the new
syntax or semantics associated with the future statement. This can,
@ -855,64 +854,14 @@ program.)
\strong{Programmer's note:}
the \keyword{global} is a directive to the parser. It
applies only to code parsed at the same time as the \keyword{global}
statement. In particular, a \keyword{global} statement contained in an
\keyword{exec} statement does not affect the code block \emph{containing}
the \keyword{exec} statement, and code contained in an \keyword{exec}
statement is unaffected by \keyword{global} statements in the code
containing the \keyword{exec} statement. The same applies to the
statement. In particular, a \keyword{global} statement contained in a
string or code object supplied to the builtin \function{exec()} function
does not affect the code block \emph{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
\function{eval()}, \function{execfile()} and \function{compile()} functions.
\stindex{exec}
\bifuncindex{exec}
\bifuncindex{eval}
\bifuncindex{execfile}
\bifuncindex{compile}
\section{The \keyword{exec} statement \label{exec}}
\stindex{exec}
\begin{productionlist}
\production{exec_stmt}
{"exec" \token{expression}
["in" \token{expression} ["," \token{expression}]]}
\end{productionlist}
This statement supports dynamic execution of Python code. The first
expression should evaluate to either a string, an open file object, or
a code object. If it is a string, the string is parsed as a suite of
Python statements which is then executed (unless a syntax error
occurs). If it is an open file, the file is parsed until \EOF{} and
executed. If it is a code object, it is simply executed. In all
cases, the code that's executed is expected to be valid as file
input (see section~\ref{file-input}, ``File input''). Be aware that
the \keyword{return} and \keyword{yield} statements may not be used
outside of function definitions even within the context of code passed
to the \keyword{exec} statement.
In all cases, if the optional parts are omitted, the code is executed
in the current scope. If only the first expression after \keyword{in}
is specified, it should be a dictionary, which will be used for both
the global and the local variables. If two expressions are given,
they are used for the global and local variables, respectively.
If provided, \var{locals} can be any mapping object.
\versionchanged[formerly \var{locals} was required to be a dictionary]{2.4}
As a side effect, an implementation may insert additional keys into
the dictionaries given besides those corresponding to variable names
set by the executed code. For example, the current implementation
may add a reference to the dictionary of the built-in module
\module{__builtin__} under the key \code{__builtins__} (!).
\ttindex{__builtins__}
\refbimodindex{__builtin__}
\strong{Programmer's hints:}
dynamic evaluation of expressions is supported by the built-in
function \function{eval()}. The built-in functions
\function{globals()} and \function{locals()} return the current global
and local dictionary, respectively, which may be useful to pass around
for use by \keyword{exec}.
\bifuncindex{eval}
\bifuncindex{globals}
\bifuncindex{locals}

View File

@ -62,7 +62,7 @@ This syntax is used in the following situations:
\item when parsing a module;
\item when parsing a string passed to the \keyword{exec} statement;
\item when parsing a string passed to the \function{exec()} function;
\end{itemize}

View File

@ -9,7 +9,7 @@ def main():
words.sort()
colwidth = 1 + max(map(len, words))
nwords = len(words)
nrows = (nwords + ncols - 1) / ncols
nrows = (nwords + ncols - 1) // ncols
for irow in range(nrows):
for icol in range(ncols):
i = irow + icol * nrows

View File

@ -2698,7 +2698,7 @@ standard module \module{__builtin__}\refbimodindex{__builtin__}:
'__name__', 'abs', 'basestring', 'bool', 'buffer',
'callable', 'chr', 'classmethod', 'cmp', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'enumerate', 'eval', 'exec', 'execfile', 'exit', 'file', 'filter', 'float',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
'id', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
@ -4362,8 +4362,8 @@ 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 \code{exec}, \code{eval()} or
\code{evalfile()} does not consider the classname of the invoking
Notice that code passed to \code{exec()}, \code{eval()} or
\code{execfile()} does not consider the classname of the invoking
class to be the current class; this is similar to the effect of the
\code{global} statement, the effect of which is likewise restricted to
code that is byte-compiled together. The same restriction applies to

View File

@ -32,7 +32,7 @@ fplist: fpdef (',' fpdef)* [',']
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | exec_stmt | assert_stmt)
import_stmt | global_stmt | assert_stmt)
expr_stmt: testlist (augassign (yield_expr|testlist) |
('=' (yield_expr|testlist))*)
augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
@ -58,7 +58,6 @@ import_as_names: import_as_name (',' import_as_name)* [',']
dotted_as_names: dotted_as_name (',' dotted_as_name)*
dotted_name: NAME ('.' NAME)*
global_stmt: 'global' NAME (',' NAME)*
exec_stmt: 'exec' expr ['in' test [',' test]]
assert_stmt: 'assert' test [',' test]
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef

View File

@ -64,8 +64,8 @@ enum _stmt_kind {FunctionDef_kind=1, ClassDef_kind=2, Return_kind=3,
For_kind=8, While_kind=9, If_kind=10, With_kind=11,
Raise_kind=12, TryExcept_kind=13, TryFinally_kind=14,
Assert_kind=15, Import_kind=16, ImportFrom_kind=17,
Exec_kind=18, Global_kind=19, Expr_kind=20, Pass_kind=21,
Break_kind=22, Continue_kind=23};
Global_kind=18, Expr_kind=19, Pass_kind=20, Break_kind=21,
Continue_kind=22};
struct _stmt {
enum _stmt_kind kind;
union {
@ -164,12 +164,6 @@ struct _stmt {
int level;
} ImportFrom;
struct {
expr_ty body;
expr_ty globals;
expr_ty locals;
} Exec;
struct {
asdl_seq *names;
} Global;
@ -384,8 +378,6 @@ stmt_ty Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, PyArena
stmt_ty Import(asdl_seq * names, int lineno, int col_offset, PyArena *arena);
stmt_ty ImportFrom(identifier module, asdl_seq * names, int level, int lineno,
int col_offset, PyArena *arena);
stmt_ty Exec(expr_ty body, expr_ty globals, expr_ty locals, int lineno, int
col_offset, PyArena *arena);
stmt_ty Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena);
stmt_ty Expr(expr_ty value, int lineno, int col_offset, PyArena *arena);
stmt_ty Pass(int lineno, int col_offset, PyArena *arena);

View File

@ -31,54 +31,53 @@
#define dotted_as_names 286
#define dotted_name 287
#define global_stmt 288
#define exec_stmt 289
#define assert_stmt 290
#define compound_stmt 291
#define if_stmt 292
#define while_stmt 293
#define for_stmt 294
#define try_stmt 295
#define with_stmt 296
#define with_var 297
#define except_clause 298
#define suite 299
#define testlist_safe 300
#define old_test 301
#define old_lambdef 302
#define test 303
#define or_test 304
#define and_test 305
#define not_test 306
#define comparison 307
#define comp_op 308
#define expr 309
#define xor_expr 310
#define and_expr 311
#define shift_expr 312
#define arith_expr 313
#define term 314
#define factor 315
#define power 316
#define atom 317
#define listmaker 318
#define testlist_gexp 319
#define lambdef 320
#define trailer 321
#define subscriptlist 322
#define subscript 323
#define sliceop 324
#define exprlist 325
#define testlist 326
#define dictsetmaker 327
#define classdef 328
#define arglist 329
#define argument 330
#define list_iter 331
#define list_for 332
#define list_if 333
#define gen_iter 334
#define gen_for 335
#define gen_if 336
#define testlist1 337
#define encoding_decl 338
#define yield_expr 339
#define assert_stmt 289
#define compound_stmt 290
#define if_stmt 291
#define while_stmt 292
#define for_stmt 293
#define try_stmt 294
#define with_stmt 295
#define with_var 296
#define except_clause 297
#define suite 298
#define testlist_safe 299
#define old_test 300
#define old_lambdef 301
#define test 302
#define or_test 303
#define and_test 304
#define not_test 305
#define comparison 306
#define comp_op 307
#define expr 308
#define xor_expr 309
#define and_expr 310
#define shift_expr 311
#define arith_expr 312
#define term 313
#define factor 314
#define power 315
#define atom 316
#define listmaker 317
#define testlist_gexp 318
#define lambdef 319
#define trailer 320
#define subscriptlist 321
#define subscript 322
#define sliceop 323
#define exprlist 324
#define testlist 325
#define dictsetmaker 326
#define classdef 327
#define arglist 328
#define argument 329
#define list_iter 330
#define list_for 331
#define list_if 332
#define gen_iter 333
#define gen_for 334
#define gen_if 335
#define testlist1 336
#define encoding_decl 337
#define yield_expr 338

View File

@ -75,7 +75,7 @@ extern "C" {
#define LOAD_LOCALS 82
#define RETURN_VALUE 83
#define IMPORT_STAR 84
#define EXEC_STMT 85
#define YIELD_VALUE 86
#define POP_BLOCK 87
#define END_FINALLY 88

View File

@ -88,11 +88,9 @@ PyAPI_FUNC(void) PySymtable_Free(struct symtable *);
#define FREE 4
#define CELL 5
/* The following three names are used for the ste_unoptimized bit field */
/* The following two names are used for the ste_unoptimized bit field */
#define OPT_IMPORT_STAR 1
#define OPT_EXEC 2
#define OPT_BARE_EXEC 4
#define OPT_TOPLEVEL 8 /* top-level names, including eval and exec */
#define OPT_TOPLEVEL 2 /* top-level names, including eval and exec */
#define GENERATOR 1
#define GENERATOR_EXPRESSION 2

View File

@ -164,7 +164,7 @@ def _test():
else:
print "accessible"
\n"""
exec testcode
exec(testcode)
print '='*20, "Using rexec:", '='*20
import rexec
r = rexec.RExec()

View File

@ -362,7 +362,7 @@ class Bdb:
cmd = cmd+'\n'
try:
try:
exec cmd in globals, locals
exec(cmd, globals, locals)
except BdbQuit:
pass
finally:

View File

@ -72,7 +72,7 @@ import sys, os
if sys.version >= '2.3':
import UserDict
from weakref import ref
exec """
exec("""
class _iter_mixin(UserDict.DictMixin):
def _make_iter_cursor(self):
cur = _DeadlockWrap(self.db.cursor)
@ -145,7 +145,7 @@ class _iter_mixin(UserDict.DictMixin):
except _bsddb.DBCursorClosedError:
# the database was modified during iteration. abort.
return
"""
""")
else:
class _iter_mixin: pass

View File

@ -137,7 +137,7 @@ class Profile(_lsprof.Profiler):
def runctx(self, cmd, globals, locals):
self.enable()
try:
exec cmd in globals, locals
exec(cmd, globals, locals)
finally:
self.disable()
return self

View File

@ -910,7 +910,7 @@ def test(environ=os.environ):
print_environ(environ)
print_environ_usage()
def f():
exec "testing print_exception() -- <I>italics?</I>"
exec("testing print_exception() -- <I>italics?</I>")
def g(f=f):
f()
print "<H3>What follows is a test, not an actual exception:</H3>"

View File

@ -100,7 +100,7 @@ class InteractiveInterpreter:
"""
try:
exec code in self.locals
exec(code, self.locals)
except SystemExit:
raise
except:

View File

@ -440,32 +440,6 @@ class Ellipsis(Node):
def __repr__(self):
return "Ellipsis()"
class Exec(Node):
def __init__(self, expr, locals, globals, lineno=None):
self.expr = expr
self.locals = locals
self.globals = globals
self.lineno = lineno
def getChildren(self):
children = []
children.append(self.expr)
children.append(self.locals)
children.append(self.globals)
return tuple(children)
def getChildNodes(self):
nodelist = []
nodelist.append(self.expr)
if self.locals is not None:
nodelist.append(self.locals)
if self.globals is not None:
nodelist.append(self.globals)
return tuple(nodelist)
def __repr__(self):
return "Exec(%s, %s, %s)" % (repr(self.expr), repr(self.locals), repr(self.globals))
class FloorDiv(Node):
def __init__(self, (left, right), lineno=None):
self.left = left

View File

@ -762,7 +762,6 @@ class StackDepthTracker:
'PRINT_ITEM': -1,
'RETURN_VALUE': -1,
'YIELD_VALUE': -1,
'EXEC_STMT': -3,
'BUILD_CLASS': -2,
'STORE_NAME': -1,
'STORE_ATTR': -2,

View File

@ -1043,18 +1043,6 @@ class CodeGenerator:
self.emit('ROT_THREE')
self.emit('STORE_SUBSCR')
def visitExec(self, node):
self.visit(node.expr)
if node.locals is None:
self.emit('LOAD_CONST', None)
else:
self.visit(node.locals)
if node.globals is None:
self.emit('DUP_TOP')
else:
self.visit(node.globals)
self.emit('EXEC_STMT')
def visitCallFunc(self, node):
pos = 0
kw = 0

View File

@ -468,20 +468,6 @@ class Transformer:
names.append(nodelist[i][1])
return Global(names, lineno=nodelist[0][2])
def exec_stmt(self, nodelist):
# exec_stmt: 'exec' expr ['in' expr [',' expr]]
expr1 = self.com_node(nodelist[1])
if len(nodelist) >= 4:
expr2 = self.com_node(nodelist[3])
if len(nodelist) >= 6:
expr3 = self.com_node(nodelist[5])
else:
expr3 = None
else:
expr2 = expr3 = None
return Exec(expr1, expr2, expr3, lineno=nodelist[0][2])
def assert_stmt(self, nodelist):
# 'assert': test, [',' test]
expr1 = self.com_node(nodelist[1])
@ -1429,7 +1415,6 @@ _legal_node_types = [
symbol.raise_stmt,
symbol.import_stmt,
symbol.global_stmt,
symbol.exec_stmt,
symbol.assert_stmt,
symbol.if_stmt,
symbol.while_stmt,

View File

@ -1209,8 +1209,8 @@ class DocTestRunner:
# keyboard interrupts.)
try:
# Don't blink! This is where the user's code gets run.
exec compile(example.source, filename, "single",
compileflags, 1) in test.globs
exec(compile(example.source, filename, "single",
compileflags, 1), test.globs)
self.debugger.set_continue() # ==== Example Finished ====
exception = None
except KeyboardInterrupt:

View File

@ -82,11 +82,11 @@ try:
f = getattr(_hashlib, opensslFuncName)
f()
# Use the C function directly (very fast)
exec funcName + ' = f'
exec(funcName + ' = f')
except ValueError:
try:
# Use the builtin implementation directly (fast)
exec funcName + ' = __get_builtin_constructor(funcName)'
exec(funcName + ' = __get_builtin_constructor(funcName)')
except ValueError:
# this one has no builtin implementation, don't define it
pass

View File

@ -690,7 +690,7 @@ class ModifiedInterpreter(InteractiveInterpreter):
if self.rpcclt:
self.rpcclt.remotequeue("exec", "runcode", (code,), {})
else:
exec code in self.locals
exec(code, self.locals)
return 1
def runcode(self, code):
@ -711,7 +711,7 @@ class ModifiedInterpreter(InteractiveInterpreter):
elif debugger:
debugger.run(code, self.locals)
else:
exec code in self.locals
exec(code, self.locals)
except SystemExit:
if not self.tkconsole.closing:
if tkMessageBox.askyesno(

View File

@ -282,7 +282,7 @@ class Executive(object):
def runcode(self, code):
try:
self.usr_exc_info = None
exec code in self.locals
exec(code, self.locals)
except:
self.usr_exc_info = sys.exc_info()
if quitting:

View File

@ -323,7 +323,7 @@ class FancyModuleLoader(ModuleLoader):
m.__path__ = path
m.__file__ = filename
try:
exec code in m.__dict__
exec(code, m.__dict__)
except:
d = self.hooks.modules_dict()
if name in d:

View File

@ -301,7 +301,7 @@ class Importer:
# execute the code within the module's namespace
if not is_module:
try:
exec code in module.__dict__
exec(code, module.__dict__)
except:
if fqname in sys.modules:
del sys.modules[fqname]

View File

@ -25,7 +25,6 @@ kwlist = [
'elif',
'else',
'except',
'exec',
'finally',
'for',
'from',

View File

@ -1699,7 +1699,7 @@ class Tk(Misc, Wm):
base_tcl = os.path.join(home, '.%s.tcl' % baseName)
base_py = os.path.join(home, '.%s.py' % baseName)
dir = {'self': self}
exec 'from Tkinter import *' in dir
exec('from Tkinter import *', dir)
if os.path.isfile(class_tcl):
self.tk.call('source', class_tcl)
if os.path.isfile(class_py):

View File

@ -114,7 +114,6 @@ def_op('WITH_CLEANUP', 81)
def_op('LOAD_LOCALS', 82)
def_op('RETURN_VALUE', 83)
def_op('IMPORT_STAR', 84)
def_op('EXEC_STMT', 85)
def_op('YIELD_VALUE', 86)
def_op('POP_BLOCK', 87)
def_op('END_FINALLY', 88)

View File

@ -198,7 +198,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
globals = self.curframe.f_globals
try:
code = compile(line + '\n', '<stdin>', 'single')
exec code in globals, locals
exec(code, globals, locals)
except:
t, v = sys.exc_info()[:2]
if type(t) == type(''):

View File

@ -329,7 +329,7 @@ def _parse_object(file):
#
def create_full_form(inst, (fdata, odatalist)):
form = create_form(fdata)
exec 'inst.'+fdata.Name+' = form\n'
exec('inst.'+fdata.Name+' = form\n')
for odata in odatalist:
create_object_instance(inst, form, odata)
@ -338,7 +338,7 @@ def create_full_form(inst, (fdata, odatalist)):
# variable.
#
def merge_full_form(inst, form, (fdata, odatalist)):
exec 'inst.'+fdata.Name+' = form\n'
exec('inst.'+fdata.Name+' = form\n')
if odatalist[0].Class != FL.BOX:
raise error, 'merge_full_form() expects FL.BOX as first obj'
for odata in odatalist[1:]:
@ -374,7 +374,7 @@ def create_object_instance(inst, form, odata):
cbfunc = eval('inst.'+odata.Callback)
obj.set_call_back(cbfunc, odata.Argument)
if odata.Name:
exec 'inst.' + odata.Name + ' = obj\n'
exec('inst.' + odata.Name + ' = obj\n')
#
# Internal _create_object: Create the object and fill options
#

View File

@ -130,7 +130,7 @@ def assign_members(target, attrlist, exclist, prefix):
stmt = lhs + '=' + repr(value)
if debug: print 'exec', stmt
try:
exec stmt + '\n'
exec(stmt + '\n')
except KeyboardInterrupt: # Don't catch this!
raise KeyboardInterrupt
except:
@ -186,7 +186,7 @@ def build_subactuators(panel, super_act, al):
if name:
stmt = 'panel.' + name + ' = act'
if debug: print 'exec', stmt
exec stmt + '\n'
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')
@ -236,7 +236,7 @@ def build_panel(descr):
act.addact(panel)
if name:
stmt = 'panel.' + name + ' = act'
exec stmt + '\n'
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')

View File

@ -328,7 +328,7 @@ def _parse_object(file):
#
def create_full_form(inst, (fdata, odatalist)):
form = create_form(fdata)
exec 'inst.'+fdata.Name+' = form\n'
exec('inst.'+fdata.Name+' = form\n')
for odata in odatalist:
create_object_instance(inst, form, odata)
@ -337,7 +337,7 @@ def create_full_form(inst, (fdata, odatalist)):
# variable.
#
def merge_full_form(inst, form, (fdata, odatalist)):
exec 'inst.'+fdata.Name+' = form\n'
exec('inst.'+fdata.Name+' = form\n')
if odatalist[0].Class != FL.BOX:
raise error, 'merge_full_form() expects FL.BOX as first obj'
for odata in odatalist[1:]:
@ -373,7 +373,7 @@ def create_object_instance(inst, form, odata):
cbfunc = eval('inst.'+odata.Callback)
obj.set_call_back(cbfunc, odata.Argument)
if odata.Name:
exec 'inst.' + odata.Name + ' = obj\n'
exec('inst.' + odata.Name + ' = obj\n')
#
# Internal _create_object: Create the object and fill options
#

View File

@ -130,7 +130,7 @@ def assign_members(target, attrlist, exclist, prefix):
stmt = lhs + '=' + repr(value)
if debug: print 'exec', stmt
try:
exec stmt + '\n'
exec(stmt + '\n')
except KeyboardInterrupt: # Don't catch this!
raise KeyboardInterrupt
except:
@ -186,7 +186,7 @@ def build_subactuators(panel, super_act, al):
if name:
stmt = 'panel.' + name + ' = act'
if debug: print 'exec', stmt
exec stmt + '\n'
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')
@ -236,7 +236,7 @@ def build_panel(descr):
act.addact(panel)
if name:
stmt = 'panel.' + name + ' = act'
exec stmt + '\n'
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')

View File

@ -557,12 +557,12 @@ template = """
class %s(ComponentItem): want = '%s'
"""
exec template % ("Text", 'text')
exec template % ("Character", 'cha ')
exec template % ("Word", 'cwor')
exec template % ("Line", 'clin')
exec template % ("paragraph", 'cpar')
exec template % ("Window", 'cwin')
exec template % ("Document", 'docu')
exec template % ("File", 'file')
exec template % ("InsertionPoint", 'cins')
exec(template % ("Text", 'text'))
exec(template % ("Character", 'cha '))
exec(template % ("Word", 'cwor'))
exec(template % ("Line", 'clin'))
exec(template % ("paragraph", 'cpar'))
exec(template % ("Window", 'cwin'))
exec(template % ("Document", 'docu'))
exec(template % ("File", 'file'))
exec(template % ("InsertionPoint", 'cins'))

View File

@ -57,7 +57,7 @@ else:
# funny) and go.
#
del argvemulator, os, sys, marshal, _dir, _fp
exec __code__
exec(__code__)
else:
sys.stderr.write("%s: neither __main__.py nor __main__.pyc found\n"%sys.argv[0])
sys.exit(1)

View File

@ -588,7 +588,7 @@ class PimpPackage:
}
installTest = self._dict['Install-test'].strip() + '\n'
try:
exec installTest in namespace
exec(installTest, namespace)
except ImportError, arg:
return "no", str(arg)
except _scriptExc_NotInstalled, arg:
@ -757,7 +757,7 @@ class PimpPackage:
if line[0] == '#':
continue
if line[:6] == 'import':
exec line
exec(line)
continue
if line[-1] == '\n':
line = line[:-1]

View File

@ -459,7 +459,7 @@ class Profile:
self.set_cmd(cmd)
sys.setprofile(self.dispatcher)
try:
exec cmd in globals, locals
exec(cmd, globals, locals)
finally:
sys.setprofile(None)
return self

View File

@ -58,7 +58,7 @@ class FileDelegate(FileBase):
self.name = name
for m in FileBase.ok_file_methods + ('close',):
exec TEMPLATE % (m, m)
exec(TEMPLATE % (m, m))
class RHooks(ihooks.Hooks):
@ -310,7 +310,7 @@ class RExec(ihooks._Verbose):
"""
m = self.add_module('__main__')
exec code in m.__dict__
exec(code, m.__dict__)
def r_eval(self, code):
"""Evaluate code within a restricted environment.

View File

@ -29,7 +29,7 @@ def _run_code(code, run_globals, init_globals,
run_globals.update(__name__ = mod_name,
__file__ = mod_fname,
__loader__ = mod_loader)
exec code in run_globals
exec(code, run_globals)
return run_globals
def _run_module_code(code, init_globals=None,

View File

@ -135,7 +135,7 @@ def addpackage(sitedir, name, known_paths):
if line.startswith("#"):
continue
if line.startswith("import"):
exec line
exec(line)
continue
line = line.rstrip()
dir, dircase = makepath(sitedir, line)

View File

@ -191,7 +191,7 @@ class _socketobject(object):
_s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
"%s.__doc__ = _realsocket.%s.__doc__\n")
for _m in _socketmethods:
exec _s % (_m, _m, _m, _m)
exec(_s % (_m, _m, _m, _m))
del _m, _s
socket = SocketType = _socketobject

View File

@ -43,57 +43,56 @@ import_as_names = 285
dotted_as_names = 286
dotted_name = 287
global_stmt = 288
exec_stmt = 289
assert_stmt = 290
compound_stmt = 291
if_stmt = 292
while_stmt = 293
for_stmt = 294
try_stmt = 295
with_stmt = 296
with_var = 297
except_clause = 298
suite = 299
testlist_safe = 300
old_test = 301
old_lambdef = 302
test = 303
or_test = 304
and_test = 305
not_test = 306
comparison = 307
comp_op = 308
expr = 309
xor_expr = 310
and_expr = 311
shift_expr = 312
arith_expr = 313
term = 314
factor = 315
power = 316
atom = 317
listmaker = 318
testlist_gexp = 319
lambdef = 320
trailer = 321
subscriptlist = 322
subscript = 323
sliceop = 324
exprlist = 325
testlist = 326
dictmaker = 327
classdef = 328
arglist = 329
argument = 330
list_iter = 331
list_for = 332
list_if = 333
gen_iter = 334
gen_for = 335
gen_if = 336
testlist1 = 337
encoding_decl = 338
yield_expr = 339
assert_stmt = 289
compound_stmt = 290
if_stmt = 291
while_stmt = 292
for_stmt = 293
try_stmt = 294
with_stmt = 295
with_var = 296
except_clause = 297
suite = 298
testlist_safe = 299
old_test = 300
old_lambdef = 301
test = 302
or_test = 303
and_test = 304
not_test = 305
comparison = 306
comp_op = 307
expr = 308
xor_expr = 309
and_expr = 310
shift_expr = 311
arith_expr = 312
term = 313
factor = 314
power = 315
atom = 316
listmaker = 317
testlist_gexp = 318
lambdef = 319
trailer = 320
subscriptlist = 321
subscript = 322
sliceop = 323
exprlist = 324
testlist = 325
dictsetmaker = 326
classdef = 327
arglist = 328
argument = 329
list_iter = 330
list_for = 331
list_if = 332
gen_iter = 333
gen_for = 334
gen_if = 335
testlist1 = 336
encoding_decl = 337
yield_expr = 338
#--end constants--
sym_name = {}

View File

@ -16,4 +16,4 @@ import types
co = types.CodeType(0, 0, 0, 0, '\x04\x71\x00\x00', (),
(), (), '', '', 1, '')
exec co
exec(co)

View File

@ -1,5 +1,5 @@
test_cProfile
126 function calls (106 primitive calls) in 1.000 CPU seconds
127 function calls (107 primitive calls) in 1.000 CPU seconds
Ordered by: standard name
@ -14,6 +14,7 @@ test_cProfile
4 0.116 0.029 0.120 0.030 test_cProfile.py:78(helper1)
2 0.000 0.000 0.140 0.070 test_cProfile.py:89(helper2_indirect)
8 0.312 0.039 0.400 0.050 test_cProfile.py:93(helper2)
1 0.000 0.000 1.000 1.000 {exec}
12 0.000 0.000 0.012 0.001 {hasattr}
4 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
@ -44,6 +45,7 @@ test_cProfile.py:89(helper2_indirect) -> 2 0.006 0.040
2 0.078 0.100 test_cProfile.py:93(helper2)
test_cProfile.py:93(helper2) -> 8 0.064 0.080 test_cProfile.py:103(subhelper)
8 0.000 0.008 {hasattr}
{exec} -> 1 0.000 1.000 <string>:1(<module>)
{hasattr} -> 12 0.012 0.012 test_cProfile.py:115(__getattr__)
{method 'append' of 'list' objects} ->
{method 'disable' of '_lsprof.Profiler' objects} ->
@ -55,7 +57,7 @@ test_cProfile.py:93(helper2) -> 8 0.064 0.080
Function was called by...
ncalls tottime cumtime
<string>:1(<module>) <-
<string>:1(<module>) <- 1 0.000 1.000 {exec}
test_cProfile.py:103(subhelper) <- 8 0.064 0.080 test_cProfile.py:93(helper2)
test_cProfile.py:115(__getattr__) <- 16 0.016 0.016 test_cProfile.py:103(subhelper)
12 0.012 0.012 {hasattr}
@ -69,6 +71,7 @@ test_cProfile.py:78(helper1) <- 4 0.116 0.120
test_cProfile.py:89(helper2_indirect) <- 2 0.000 0.140 test_cProfile.py:60(helper)
test_cProfile.py:93(helper2) <- 6 0.234 0.300 test_cProfile.py:60(helper)
2 0.078 0.100 test_cProfile.py:89(helper2_indirect)
{exec} <-
{hasattr} <- 4 0.000 0.004 test_cProfile.py:78(helper1)
8 0.000 0.008 test_cProfile.py:93(helper2)
{method 'append' of 'list' objects} <- 4 0.000 0.000 test_cProfile.py:78(helper1)

View File

@ -39,7 +39,6 @@ raise_stmt
import_name
import_from
global_stmt
exec_stmt
assert_stmt
if_stmt
while_stmt

View File

@ -1,11 +1,12 @@
test_profile
127 function calls (107 primitive calls) in 1.000 CPU seconds
128 function calls (108 primitive calls) in 1.000 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
4 0.000 0.000 0.000 0.000 :0(append)
4 0.000 0.000 0.000 0.000 :0(exc_info)
1 0.000 0.000 1.000 1.000 :0(exec)
12 0.000 0.000 0.012 0.001 :0(hasattr)
8 0.000 0.000 0.000 0.000 :0(range)
1 0.000 0.000 0.000 0.000 :0(setprofile)
@ -28,13 +29,14 @@ test_profile
Function called...
:0(append) ->
:0(exc_info) ->
:0(exec) -> <string>:1(<module>)(1) 1.000
:0(hasattr) -> test_profile.py:115(__getattr__)(12) 0.028
:0(range) ->
:0(setprofile) ->
<string>:1(<module>) -> test_profile.py:30(testfunc)(1) 1.000
profile:0(profiler) -> profile:0(testfunc())(1) 1.000
profile:0(testfunc()) -> :0(setprofile)(1) 0.000
<string>:1(<module>)(1) 1.000
profile:0(testfunc()) -> :0(exec)(1) 1.000
:0(setprofile)(1) 0.000
test_profile.py:103(subhelper) -> :0(range)(8) 0.000
test_profile.py:115(__getattr__)(16) 0.028
test_profile.py:115(__getattr__) ->
@ -60,11 +62,12 @@ test_profile.py:93(helper2) -> :0(hasattr)(8) 0.012
Function was called by...
:0(append) <- test_profile.py:78(helper1)(4) 0.120
:0(exc_info) <- test_profile.py:78(helper1)(4) 0.120
:0(exec) <- profile:0(testfunc())(1) 1.000
:0(hasattr) <- test_profile.py:78(helper1)(4) 0.120
test_profile.py:93(helper2)(8) 0.400
:0(range) <- test_profile.py:103(subhelper)(8) 0.080
:0(setprofile) <- profile:0(testfunc())(1) 1.000
<string>:1(<module>) <- profile:0(testfunc())(1) 1.000
<string>:1(<module>) <- :0(exec)(1) 1.000
profile:0(profiler) <-
profile:0(testfunc()) <- profile:0(profiler)(1) 0.000
test_profile.py:103(subhelper) <- test_profile.py:93(helper2)(8) 0.400

View File

@ -15,7 +15,7 @@ class AllTest(unittest.TestCase):
def check_all(self, modname):
names = {}
try:
exec "import %s" % modname in names
exec("import %s" % modname, names)
except ImportError:
# Silent fail here seems the best route since some modules
# may not be available in all environments.
@ -23,7 +23,7 @@ class AllTest(unittest.TestCase):
verify(hasattr(sys.modules[modname], "__all__"),
"%s has no __all__ attribute" % modname)
names = {}
exec "from %s import *" % modname in names
exec("from %s import *" % modname, names)
if "__builtins__" in names:
del names["__builtins__"]
keys = set(names)

View File

@ -50,8 +50,6 @@ exec_tests = [
"import sys",
# ImportFrom
"from sys import v",
# Exec
"exec 'v'",
# Global
"global v",
# Expr
@ -169,7 +167,6 @@ exec_results = [
('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
('Module', [('Exec', (1, 0), ('Str', (1, 5), 'v'), None, None)]),
('Module', [('Global', (1, 0), ['v'])]),
('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
('Module', [('Pass', (1, 0))]),

View File

@ -302,7 +302,7 @@ class RatTestCase(unittest.TestCase):
self.assertEqual(10.0, Rat(10))
def test_future_div(self):
exec future_test
exec(future_test)
# XXX Ran out of steam; TO DO: divmod, div, future division

View File

@ -395,6 +395,29 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(IOError, execfile, os.curdir)
self.assertRaises(IOError, execfile, "I_dont_exist")
def test_exec(self):
g = {}
exec('z = 1', g)
if '__builtins__' in g:
del g['__builtins__']
self.assertEqual(g, {'z': 1})
exec(u'z = 1+1', g)
if '__builtins__' in g:
del g['__builtins__']
self.assertEqual(g, {'z': 2})
g = {}
l = {}
import warnings
warnings.filterwarnings("ignore", "global statement", module="<string>")
exec('global a; a = 1; b = 2', g, l)
if '__builtins__' in g:
del g['__builtins__']
if '__builtins__' in l:
del l['__builtins__']
self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
def test_filter(self):
self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
@ -1172,7 +1195,7 @@ class BuiltinTest(unittest.TestCase):
"max(1, 2, key=1)", # keyfunc is not callable
):
try:
exec(stmt) in globals()
exec(stmt, globals())
except TypeError:
pass
else:
@ -1218,7 +1241,7 @@ class BuiltinTest(unittest.TestCase):
"min(1, 2, key=1)", # keyfunc is not callable
):
try:
exec(stmt) in globals()
exec(stmt, globals())
except TypeError:
pass
else:

View File

@ -136,7 +136,7 @@ def __%(method)s__(self, *args):
d = {}
for method in testmeths:
exec method_template % locals() in d
exec(method_template % locals(), d)
for k in d:
setattr(AllTests, k, d[k])
del d, k
@ -291,7 +291,7 @@ def check_exc(stmt, exception):
"""Raise TestFailed if executing 'stmt' does not raise 'exception'
"""
try:
exec stmt
exec(stmt)
except exception:
pass
else:

View File

@ -29,8 +29,8 @@ class CodeopTests(unittest.TestCase):
saved_stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
try:
exec code in d
exec compile(str,"<input>","single") in r
exec(code, d)
exec(compile(str,"<input>","single"), r)
finally:
sys.stdout = saved_stdout
elif symbol == 'eval':

View File

@ -19,17 +19,17 @@ class TestSpecifics(unittest.TestCase):
self.assertRaises(SyntaxError, eval, 'lambda a,a=1:0')
self.assertRaises(SyntaxError, eval, 'lambda a=1,a=1:0')
try:
exec 'def f(a, a): pass'
exec('def f(a, a): pass')
self.fail("duplicate arguments")
except SyntaxError:
pass
try:
exec 'def f(a = 0, a = 1): pass'
exec('def f(a = 0, a = 1): pass')
self.fail("duplicate keyword arguments")
except SyntaxError:
pass
try:
exec 'def f(a): global a; a = 1'
exec('def f(a): global a; a = 1')
self.fail("variable is global and local")
except SyntaxError:
pass
@ -39,7 +39,7 @@ class TestSpecifics(unittest.TestCase):
def test_duplicate_global_local(self):
try:
exec 'def f(a): global a; a = 1'
exec('def f(a): global a; a = 1')
self.fail("variable is global and local")
except SyntaxError:
pass
@ -59,22 +59,22 @@ class TestSpecifics(unittest.TestCase):
m = M()
g = globals()
exec 'z = a' in g, m
exec('z = a', g, m)
self.assertEqual(m.results, ('z', 12))
try:
exec 'z = b' in g, m
exec('z = b', g, m)
except NameError:
pass
else:
self.fail('Did not detect a KeyError')
exec 'z = dir()' in g, m
exec('z = dir()', g, m)
self.assertEqual(m.results, ('z', list('xyz')))
exec 'z = globals()' in g, m
exec('z = globals()', g, m)
self.assertEqual(m.results, ('z', g))
exec 'z = locals()' in g, m
exec('z = locals()', g, m)
self.assertEqual(m.results, ('z', m))
try:
exec 'z = b' in m
exec('z = b', m)
except TypeError:
pass
else:
@ -85,7 +85,7 @@ class TestSpecifics(unittest.TestCase):
pass
m = A()
try:
exec 'z = a' in g, m
exec('z = a', g, m)
except TypeError:
pass
else:
@ -98,11 +98,12 @@ class TestSpecifics(unittest.TestCase):
return 12
return dict.__getitem__(self, key)
d = D()
exec 'z = a' in g, d
exec('z = a', g, d)
self.assertEqual(d['z'], 12)
def test_extended_arg(self):
longexpr = 'x = x or ' + '-x' * 2500
g = {}
code = '''
def f(x):
%s
@ -121,8 +122,8 @@ def f(x):
# EXTENDED_ARG/JUMP_ABSOLUTE here
return x
''' % ((longexpr,)*10)
exec code
self.assertEqual(f(5), 0)
exec(code, g)
self.assertEqual(g['f'](5), 0)
def test_complex_args(self):
@ -146,7 +147,7 @@ def f(x):
def test_argument_order(self):
try:
exec 'def f(a=1, (b, c)): pass'
exec('def f(a=1, (b, c)): pass')
self.fail("non-default args after default")
except SyntaxError:
pass

View File

@ -61,7 +61,7 @@ class CompilerTest(unittest.TestCase):
c = compiler.compile("try:\n 1/0\nexcept:\n e = 1\nfinally:\n f = 1",
"<string>", "exec")
dct = {}
exec c in dct
exec(c, dct)
self.assertEquals(dct.get('e'), 1)
self.assertEquals(dct.get('f'), 1)
@ -73,7 +73,7 @@ class CompilerTest(unittest.TestCase):
self.assert_('__doc__' in c.co_names)
c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
g = {}
exec c in g
exec(c, g)
self.assertEquals(g['f'].__doc__, "doc")
def testLineNo(self):
@ -113,7 +113,7 @@ class CompilerTest(unittest.TestCase):
'<string>',
'exec')
dct = {}
exec c in dct
exec(c, dct)
self.assertEquals(dct.get('result'), 3)
def testGenExp(self):

View File

@ -55,7 +55,7 @@ def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
if verbose: print "checking", stmt
dict = {'a': deepcopy(a), 'b': b}
exec stmt in dict
exec(stmt, dict)
vereq(dict['a'], res)
t = type(a)
m = getattr(t, meth)
@ -73,7 +73,7 @@ def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
if verbose: print "checking", stmt
dict = {'a': deepcopy(a), 'b': b, 'c': c}
exec stmt in dict
exec(stmt, dict)
vereq(dict['a'], res)
t = type(a)
m = getattr(t, meth)
@ -91,7 +91,7 @@ def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
if verbose: print "checking", stmt
dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
exec stmt in dict
exec(stmt, dict)
vereq(dict['a'], res)
t = type(a)
while meth not in t.__dict__:
@ -3943,7 +3943,7 @@ def notimplemented():
def check(expr, x, y):
try:
exec expr in {'x': x, 'y': y, 'operator': operator}
exec(expr, {'x': x, 'y': y, 'operator': operator})
except TypeError:
pass
else:

View File

@ -67,7 +67,7 @@ statement or the built-in function eval():
>>> print sorted(a.keys())
[1, 2]
>>> exec "x = 3; print x" in a
>>> exec("x = 3; print x", a)
3
>>> print sorted(a.keys(), key=lambda x: (str(type(x)), x))
[1, 2, '__builtins__', 'x']

View File

@ -135,7 +135,7 @@ class DisTests(unittest.TestCase):
def func(count):
namespace = {}
func = "def foo():\n " + "".join(["\n "] * count + ["spam\n"])
exec func in namespace
exec(func, namespace)
return namespace['foo']
# Test all small ranges

View File

@ -2366,8 +2366,8 @@ def old_test4(): """
... '''>>> assert 1 < 2
... '''
... \"""
>>> exec test_data in m1.__dict__
>>> exec test_data in m2.__dict__
>>> exec(test_data, m1.__dict__)
>>> exec(test_data, m2.__dict__)
>>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tests that objects outside m1 are excluded:

View File

@ -87,7 +87,7 @@ class ExceptionTests(unittest.TestCase):
self.raise_catch(RuntimeError, "RuntimeError")
self.raise_catch(SyntaxError, "SyntaxError")
try: exec '/\n'
try: exec('/\n')
except SyntaxError: pass
self.raise_catch(IndentationError, "IndentationError")

View File

@ -278,7 +278,7 @@ def test_func_name():
cantset(f, "__name__", 1)
# test that you can access func.__name__ in restricted mode
s = """def f(): pass\nf.__name__"""
exec s in {'__builtins__':{}}
exec(s, {'__builtins__':{}})
def test_func_code():

View File

@ -153,7 +153,7 @@ def test_function():
# Tricky: f -> d -> f, code should call d.clear() after the exec to
# break the cycle.
d = {}
exec("def f(): pass\n") in d
exec("def f(): pass\n", d)
gc.collect()
del d
expect(gc.collect(), 2, "function")

View File

@ -10,7 +10,7 @@ def expectException(teststr, expected, failure=AssertionError):
"""Executes a statement passed in teststr, and raises an exception
(failure) if the expected exception is *not* raised."""
try:
exec teststr
exec(teststr)
except expected:
pass
else:

View File

@ -449,42 +449,6 @@ def f():
global a, b
global one, two, three, four, five, six, seven, eight, nine, ten
print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]
def f():
z = None
del z
exec 'z=1+1\n'
if z != 2: raise TestFailed, 'exec \'z=1+1\'\\n'
del z
exec 'z=1+1'
if z != 2: raise TestFailed, 'exec \'z=1+1\''
z = None
del z
import types
if hasattr(types, "UnicodeType"):
exec r"""if 1:
exec u'z=1+1\n'
if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n'
del z
exec u'z=1+1'
if z != 2: raise TestFailed, 'exec u\'z=1+1\''
"""
f()
g = {}
exec 'z = 1' in g
if '__builtins__' in g: del g['__builtins__']
if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g'
g = {}
l = {}
import warnings
warnings.filterwarnings("ignore", "global statement", module="<string>")
exec 'global a; a = 1; b = 2' in g, l
if '__builtins__' in g: del g['__builtins__']
if '__builtins__' in l: del l['__builtins__']
if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l)
print "assert_stmt" # assert_stmt: 'assert' test [',' test]
assert 1
assert 1, 1

View File

@ -107,7 +107,7 @@ def test_module_with_large_stack(module):
sys.path.append('')
# this used to crash
exec 'import ' + module
exec('import ' + module)
# cleanup
del sys.path[-1]

View File

@ -81,7 +81,7 @@ class TestImporter:
mod.__loader__ = self
if ispkg:
mod.__path__ = self._get__path__()
exec code in mod.__dict__
exec(code, mod.__dict__)
return mod

View File

@ -199,7 +199,7 @@ class TestRetrievingSourceCode(GetSourceBase):
m = sys.modules[name] = module(name)
m.__file__ = "<string>" # hopefully not a real filename...
m.__loader__ = "dummy" # pretend the filename is understood by a loader
exec "def x(): pass" in m.__dict__
exec("def x(): pass", m.__dict__)
self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>')
del sys.modules[name]
inspect.getmodule(compile('a=10','','single'))

View File

@ -49,7 +49,7 @@ class Test_MultibyteCodec(unittest.TestCase):
try:
for enc in ALL_CJKENCODINGS:
print >> open(TESTFN, 'w'), '# coding:', enc
exec open(TESTFN)
execfile(TESTFN)
finally:
os.unlink(TESTFN)

View File

@ -30,7 +30,7 @@ for stmt in ['d[x2] = 2',
'd.pop(x2)',
'd.update({x2: 2})']:
try:
exec stmt
exec(stmt)
except RuntimeError:
print "%s: caught the RuntimeError outside" % (stmt,)
else:

View File

@ -429,7 +429,7 @@ class CompileTestCase(unittest.TestCase):
st = parser.suite('x = 2; y = x + 3')
code = parser.compilest(st)
globs = {}
exec code in globs
exec(code, globs)
self.assertEquals(globs['y'], 5)
def test_compile_error(self):

View File

@ -205,15 +205,6 @@ def unoptimized_clash2():
return f
""")
# XXX could allow this for exec with const argument, but what's the point
check_syntax("""\
def error(y):
exec "a = 1"
def f(x):
return x + y
return f
""")
check_syntax("""\
def f(x):
def g():
@ -230,7 +221,7 @@ def f():
# and verify a few cases that should work
exec """
exec("""
def noproblem1():
from string import *
f = lambda x:x
@ -245,7 +236,7 @@ def noproblem3():
def f(x):
global y
y = x
"""
""")
print "12. lambdas"
@ -526,7 +517,7 @@ else:
print "eval() should have failed, because code contained free vars"
try:
exec g.func_code
exec(g.func_code)
except TypeError:
pass
else:

View File

@ -24,7 +24,7 @@ class Tests(unittest.TestCase):
# is correct
c = compile(s, '<string>', 'single')
vals = {}
exec c in vals
exec(c, vals)
assert vals['a'] == 1
assert vals['b'] == 2

View File

@ -44,22 +44,22 @@ hName = sys.argv[1]
# setup our creatorFunc to test the requested hash
#
if hName in ('_md5', '_sha'):
exec 'import '+hName
exec 'creatorFunc = '+hName+'.new'
exec('import '+hName)
exec('creatorFunc = '+hName+'.new')
print "testing speed of old", hName, "legacy interface"
elif hName == '_hashlib' and len(sys.argv) > 3:
import _hashlib
exec 'creatorFunc = _hashlib.%s' % sys.argv[2]
exec('creatorFunc = _hashlib.%s' % sys.argv[2])
print "testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])
elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec 'creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2]
exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
print "testing speed of _hashlib.new(%r)" % sys.argv[2]
elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
creatorFunc = getattr(hashlib, hName)
print "testing speed of hashlib."+hName, getattr(hashlib, hName)
else:
exec "creatorFunc = lambda x=hashlib.new : x(%r)" % hName
exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName)
print "testing speed of hashlib.new(%r)" % hName
try:

View File

@ -115,7 +115,7 @@ class Timer:
self.src = src # Save for traceback display
code = compile(src, dummy_src_name, "exec")
ns = {}
exec code in globals(), ns
exec(code, globals(), ns)
self.inner = ns["inner"]
def print_exc(self, file=None):

View File

@ -484,7 +484,7 @@ class Trace:
sys.settrace(self.globaltrace)
threading.settrace(self.globaltrace)
try:
exec cmd in dict, dict
exec(cmd, dict, dict)
finally:
if not self.donothing:
sys.settrace(None)
@ -497,7 +497,7 @@ class Trace:
sys.settrace(self.globaltrace)
threading.settrace(self.globaltrace)
try:
exec cmd in globals, locals
exec(cmd, globals, locals)
finally:
if not self.donothing:
sys.settrace(None)

View File

@ -6,5 +6,5 @@ python|Python|py:\
:pb=^\d?(def|class)\d\p(\d|\\|\(|\:):\
:cb=#:ce=$:sb=":se=\e":lb=':le=\e':\
:kw=assert and break class continue def del elif else except\
exec finally for from global if import in is lambda not or\
finally for from global if import in is lambda not or\
pass print raise return try while yield:

View File

@ -848,7 +848,7 @@ VALIDATER(raise_stmt); VALIDATER(import_stmt);
VALIDATER(import_name); VALIDATER(import_from);
VALIDATER(global_stmt); VALIDATER(list_if);
VALIDATER(assert_stmt); VALIDATER(list_for);
VALIDATER(exec_stmt); VALIDATER(compound_stmt);
VALIDATER(compound_stmt);
VALIDATER(while); VALIDATER(for);
VALIDATER(try); VALIDATER(except_clause);
VALIDATER(test); VALIDATER(and_test);
@ -1465,8 +1465,7 @@ validate_small_stmt(node *tree)
|| (ntype == flow_stmt)
|| (ntype == import_stmt)
|| (ntype == global_stmt)
|| (ntype == assert_stmt)
|| (ntype == exec_stmt))
|| (ntype == assert_stmt))
res = validate_node(CHILD(tree, 0));
else {
res = 0;
@ -1888,32 +1887,6 @@ validate_global_stmt(node *tree)
}
/* exec_stmt:
*
* 'exec' expr ['in' test [',' test]]
*/
static int
validate_exec_stmt(node *tree)
{
int nch = NCH(tree);
int res = (validate_ntype(tree, exec_stmt)
&& ((nch == 2) || (nch == 4) || (nch == 6))
&& validate_name(CHILD(tree, 0), "exec")
&& validate_expr(CHILD(tree, 1)));
if (!res && !PyErr_Occurred())
err_string("illegal exec statement");
if (res && (nch > 2))
res = (validate_name(CHILD(tree, 2), "in")
&& validate_test(CHILD(tree, 3)));
if (res && (nch == 6))
res = (validate_comma(CHILD(tree, 4))
&& validate_test(CHILD(tree, 5)));
return (res);
}
/* assert_stmt:
*
* 'assert' test [',' test]
@ -2914,7 +2887,7 @@ validate_node(node *tree)
case small_stmt:
/*
* expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt
* | import_stmt | global_stmt | exec_stmt | assert_stmt
* | import_stmt | global_stmt | assert_stmt
*/
res = validate_small_stmt(tree);
break;
@ -2984,9 +2957,6 @@ validate_node(node *tree)
case global_stmt:
res = validate_global_stmt(tree);
break;
case exec_stmt:
res = validate_exec_stmt(tree);
break;
case assert_stmt:
res = validate_assert_stmt(tree);
break;

View File

@ -73,8 +73,7 @@ init_symtable(void)
PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock);
PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR);
PyModule_AddIntConstant(m, "OPT_EXEC", OPT_EXEC);
PyModule_AddIntConstant(m, "OPT_BARE_EXEC", OPT_BARE_EXEC);
PyModule_AddIntConstant(m, "OPT_TOPLEVEL", OPT_TOPLEVEL);
PyModule_AddIntConstant(m, "LOCAL", LOCAL);
PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT);

View File

@ -36,11 +36,6 @@ module Python version "$Revision$"
| Import(alias* names)
| ImportFrom(identifier module, alias* names, int? level)
-- Doesn't capture requirement that locals must be
-- defined if globals is
-- still supports use as a function!
| Exec(expr body, expr? globals, expr? locals)
| Global(identifier* names)
| Expr(expr value)
| Pass | Break | Continue

View File

@ -123,12 +123,6 @@ static char *ImportFrom_fields[]={
"names",
"level",
};
static PyTypeObject *Exec_type;
static char *Exec_fields[]={
"body",
"globals",
"locals",
};
static PyTypeObject *Global_type;
static char *Global_fields[]={
"names",
@ -494,8 +488,6 @@ static int init_types(void)
ImportFrom_type = make_type("ImportFrom", stmt_type, ImportFrom_fields,
3);
if (!ImportFrom_type) return 0;
Exec_type = make_type("Exec", stmt_type, Exec_fields, 3);
if (!Exec_type) return 0;
Global_type = make_type("Global", stmt_type, Global_fields, 1);
if (!Global_type) return 0;
Expr_type = make_type("Expr", stmt_type, Expr_fields, 1);
@ -1169,30 +1161,6 @@ ImportFrom(identifier module, asdl_seq * names, int level, int lineno, int
return p;
}
stmt_ty
Exec(expr_ty body, expr_ty globals, expr_ty locals, int lineno, int col_offset,
PyArena *arena)
{
stmt_ty p;
if (!body) {
PyErr_SetString(PyExc_ValueError,
"field body is required for Exec");
return NULL;
}
p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
if (!p) {
PyErr_NoMemory();
return NULL;
}
p->kind = Exec_kind;
p->v.Exec.body = body;
p->v.Exec.globals = globals;
p->v.Exec.locals = locals;
p->lineno = lineno;
p->col_offset = col_offset;
return p;
}
stmt_ty
Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena)
{
@ -2274,25 +2242,6 @@ ast2obj_stmt(void* _o)
goto failed;
Py_DECREF(value);
break;
case Exec_kind:
result = PyType_GenericNew(Exec_type, NULL, NULL);
if (!result) goto failed;
value = ast2obj_expr(o->v.Exec.body);
if (!value) goto failed;
if (PyObject_SetAttrString(result, "body", value) == -1)
goto failed;
Py_DECREF(value);
value = ast2obj_expr(o->v.Exec.globals);
if (!value) goto failed;
if (PyObject_SetAttrString(result, "globals", value) == -1)
goto failed;
Py_DECREF(value);
value = ast2obj_expr(o->v.Exec.locals);
if (!value) goto failed;
if (PyObject_SetAttrString(result, "locals", value) == -1)
goto failed;
Py_DECREF(value);
break;
case Global_kind:
result = PyType_GenericNew(Global_type, NULL, NULL);
if (!result) goto failed;
@ -3082,7 +3031,6 @@ init_ast(void)
return;
if (PyDict_SetItemString(d, "ImportFrom", (PyObject*)ImportFrom_type) <
0) return;
if (PyDict_SetItemString(d, "Exec", (PyObject*)Exec_type) < 0) return;
if (PyDict_SetItemString(d, "Global", (PyObject*)Global_type) < 0)
return;
if (PyDict_SetItemString(d, "Expr", (PyObject*)Expr_type) < 0) return;

View File

@ -2399,37 +2399,6 @@ ast_for_global_stmt(struct compiling *c, const node *n)
return Global(s, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_exec_stmt(struct compiling *c, const node *n)
{
expr_ty expr1, globals = NULL, locals = NULL;
int n_children = NCH(n);
if (n_children != 2 && n_children != 4 && n_children != 6) {
PyErr_Format(PyExc_SystemError,
"poorly formed 'exec' statement: %d parts to statement",
n_children);
return NULL;
}
/* exec_stmt: 'exec' expr ['in' test [',' test]] */
REQ(n, exec_stmt);
expr1 = ast_for_expr(c, CHILD(n, 1));
if (!expr1)
return NULL;
if (n_children >= 4) {
globals = ast_for_expr(c, CHILD(n, 3));
if (!globals)
return NULL;
}
if (n_children == 6) {
locals = ast_for_expr(c, CHILD(n, 5));
if (!locals)
return NULL;
}
return Exec(expr1, globals, locals, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_assert_stmt(struct compiling *c, const node *n)
{
@ -2944,8 +2913,7 @@ ast_for_stmt(struct compiling *c, const node *n)
REQ(n, small_stmt);
n = CHILD(n, 0);
/* small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt
| flow_stmt | import_stmt | global_stmt | exec_stmt
| assert_stmt
| flow_stmt | import_stmt | global_stmt | assert_stmt
*/
switch (TYPE(n)) {
case expr_stmt:
@ -2962,8 +2930,6 @@ ast_for_stmt(struct compiling *c, const node *n)
return ast_for_import_stmt(c, n);
case global_stmt:
return ast_for_global_stmt(c, n);
case exec_stmt:
return ast_for_exec_stmt(c, n);
case assert_stmt:
return ast_for_assert_stmt(c, n);
default:

View File

@ -403,7 +403,7 @@ PyDoc_STRVAR(compile_doc,
"compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
\n\
Compile the source string (a Python module, statement or expression)\n\
into a code object that can be executed by the exec statement or eval().\n\
into a code object that can be executed by exec() or eval().\n\
The filename will be used for run-time error messages.\n\
The mode must be 'exec' to compile a module, 'single' to compile a\n\
single (interactive) statement, or 'eval' to compile an expression.\n\
@ -543,6 +543,114 @@ The globals must be a dictionary and locals can be any mappping,\n\
defaulting to the current globals and locals.\n\
If only globals is given, locals defaults to it.\n");
static PyObject *
builtin_exec(PyObject *self, PyObject *args)
{
PyObject *v;
PyObject *prog, *globals = Py_None, *locals = Py_None;
int plain = 0;
if (!PyArg_ParseTuple(args, "O|OO:exec", &prog, &globals, &locals))
return NULL;
if (globals == Py_None) {
globals = PyEval_GetGlobals();
if (locals == Py_None) {
locals = PyEval_GetLocals();
plain = 1;
}
if (!globals || !locals) {
PyErr_SetString(PyExc_SystemError,
"globals and locals cannot be NULL");
return NULL;
}
}
else if (locals == Py_None)
locals = globals;
if (!PyString_Check(prog) &&
!PyUnicode_Check(prog) &&
!PyCode_Check(prog) &&
!PyFile_Check(prog)) {
PyErr_Format(PyExc_TypeError,
"exec() arg 1 must be a string, file, or code "
"object, not %.100s", prog->ob_type->tp_name);
return NULL;
}
if (!PyDict_Check(globals)) {
PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.100s",
globals->ob_type->tp_name);
return NULL;
}
if (!PyMapping_Check(locals)) {
PyErr_Format(PyExc_TypeError,
"arg 3 must be a mapping or None, not %.100s",
locals->ob_type->tp_name);
return NULL;
}
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
if (PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins()) != 0)
return NULL;
}
if (PyCode_Check(prog)) {
if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
PyErr_SetString(PyExc_TypeError,
"code object passed to exec() may not "
"contain free variables");
return NULL;
}
v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
}
else if (PyFile_Check(prog)) {
FILE *fp = PyFile_AsFile(prog);
char *name = PyString_AsString(PyFile_Name(prog));
PyCompilerFlags cf;
cf.cf_flags = 0;
if (PyEval_MergeCompilerFlags(&cf))
v = PyRun_FileFlags(fp, name, Py_file_input, globals,
locals, &cf);
else
v = PyRun_File(fp, name, Py_file_input, globals,
locals);
}
else {
PyObject *tmp = NULL;
char *str;
PyCompilerFlags cf;
cf.cf_flags = 0;
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(prog)) {
tmp = PyUnicode_AsUTF8String(prog);
if (tmp == NULL)
return NULL;
prog = tmp;
cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
}
#endif
if (PyString_AsStringAndSize(prog, &str, NULL))
return NULL;
if (PyEval_MergeCompilerFlags(&cf))
v = PyRun_StringFlags(str, Py_file_input, globals,
locals, &cf);
else
v = PyRun_String(str, Py_file_input, globals, locals);
Py_XDECREF(tmp);
}
if (v == NULL)
return NULL;
Py_DECREF(v);
Py_RETURN_NONE;
}
PyDoc_STRVAR(exec_doc,
"exec(object[, globals[, locals]])\n\
\n\
Read and execute code from a object, which can be a string, a code\n\
object or a file object.\n\
The globals and locals are dictionaries, defaulting to the current\n\
globals and locals. If only globals is given, locals defaults to it.");
static PyObject *
builtin_execfile(PyObject *self, PyObject *args)
@ -1884,6 +1992,7 @@ static PyMethodDef builtin_methods[] = {
{"dir", builtin_dir, METH_VARARGS, dir_doc},
{"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
{"eval", builtin_eval, METH_VARARGS, eval_doc},
{"exec", builtin_exec, METH_VARARGS, exec_doc},
{"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
{"filter", builtin_filter, METH_VARARGS, filter_doc},
{"getattr", builtin_getattr, METH_VARARGS, getattr_doc},

View File

@ -118,8 +118,6 @@ static PyObject * cmp_outcome(int, PyObject *, PyObject *);
static PyObject * import_from(PyObject *, PyObject *);
static int import_all_from(PyObject *, PyObject *);
static PyObject * build_class(PyObject *, PyObject *, PyObject *);
static int exec_statement(PyFrameObject *,
PyObject *, PyObject *, PyObject *);
static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *);
static void reset_exc_info(PyThreadState *);
static void format_exc_check_arg(PyObject *, char *, PyObject *);
@ -580,7 +578,6 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
It's a case-by-case judgement. I'll use intr1 for the following
cases:
EXEC_STMT
IMPORT_STAR
IMPORT_FROM
CALL_FUNCTION (and friends)
@ -1622,19 +1619,6 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
why = WHY_YIELD;
goto fast_yield;
case EXEC_STMT:
w = TOP();
v = SECOND();
u = THIRD();
STACKADJ(-3);
READ_TIMESTAMP(intr0);
err = exec_statement(f, u, v, w);
READ_TIMESTAMP(intr1);
Py_DECREF(u);
Py_DECREF(v);
Py_DECREF(w);
break;
case POP_BLOCK:
{
PyTryBlock *b = PyFrame_BlockPop(f);
@ -4072,107 +4056,6 @@ build_class(PyObject *methods, PyObject *bases, PyObject *name)
return result;
}
static int
exec_statement(PyFrameObject *f, PyObject *prog, PyObject *globals,
PyObject *locals)
{
int n;
PyObject *v;
int plain = 0;
if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
((n = PyTuple_Size(prog)) == 2 || n == 3)) {
/* Backward compatibility hack */
globals = PyTuple_GetItem(prog, 1);
if (n == 3)
locals = PyTuple_GetItem(prog, 2);
prog = PyTuple_GetItem(prog, 0);
}
if (globals == Py_None) {
globals = PyEval_GetGlobals();
if (locals == Py_None) {
locals = PyEval_GetLocals();
plain = 1;
}
if (!globals || !locals) {
PyErr_SetString(PyExc_SystemError,
"globals and locals cannot be NULL");
return -1;
}
}
else if (locals == Py_None)
locals = globals;
if (!PyString_Check(prog) &&
!PyUnicode_Check(prog) &&
!PyCode_Check(prog) &&
!PyFile_Check(prog)) {
PyErr_SetString(PyExc_TypeError,
"exec: arg 1 must be a string, file, or code object");
return -1;
}
if (!PyDict_Check(globals)) {
PyErr_SetString(PyExc_TypeError,
"exec: arg 2 must be a dictionary or None");
return -1;
}
if (!PyMapping_Check(locals)) {
PyErr_SetString(PyExc_TypeError,
"exec: arg 3 must be a mapping or None");
return -1;
}
if (PyDict_GetItemString(globals, "__builtins__") == NULL)
PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
if (PyCode_Check(prog)) {
if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
PyErr_SetString(PyExc_TypeError,
"code object passed to exec may not contain free variables");
return -1;
}
v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
}
else if (PyFile_Check(prog)) {
FILE *fp = PyFile_AsFile(prog);
char *name = PyString_AsString(PyFile_Name(prog));
PyCompilerFlags cf;
cf.cf_flags = 0;
if (PyEval_MergeCompilerFlags(&cf))
v = PyRun_FileFlags(fp, name, Py_file_input, globals,
locals, &cf);
else
v = PyRun_File(fp, name, Py_file_input, globals,
locals);
}
else {
PyObject *tmp = NULL;
char *str;
PyCompilerFlags cf;
cf.cf_flags = 0;
#ifdef Py_USING_UNICODE
if (PyUnicode_Check(prog)) {
tmp = PyUnicode_AsUTF8String(prog);
if (tmp == NULL)
return -1;
prog = tmp;
cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
}
#endif
if (PyString_AsStringAndSize(prog, &str, NULL))
return -1;
if (PyEval_MergeCompilerFlags(&cf))
v = PyRun_StringFlags(str, Py_file_input, globals,
locals, &cf);
else
v = PyRun_String(str, Py_file_input, globals, locals);
Py_XDECREF(tmp);
}
if (plain)
PyFrame_LocalsToFast(f, 0);
if (v == NULL)
return -1;
Py_DECREF(v);
return 0;
}
static void
format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj)
{

View File

@ -814,8 +814,6 @@ opcode_stack_effect(int opcode, int oparg)
return -1;
case IMPORT_STAR:
return -1;
case EXEC_STMT:
return -3;
case YIELD_VALUE:
return 0;
@ -2112,21 +2110,6 @@ compiler_visit_stmt(struct compiler *c, stmt_ty s)
return compiler_import(c, s);
case ImportFrom_kind:
return compiler_from_import(c, s);
case Exec_kind:
VISIT(c, expr, s->v.Exec.body);
if (s->v.Exec.globals) {
VISIT(c, expr, s->v.Exec.globals);
if (s->v.Exec.locals) {
VISIT(c, expr, s->v.Exec.locals);
} else {
ADDOP(c, DUP_TOP);
}
} else {
ADDOP_O(c, LOAD_CONST, Py_None, consts);
ADDOP(c, DUP_TOP);
}
ADDOP(c, EXEC_STMT);
break;
case Global_kind:
break;
case Expr_kind:

File diff suppressed because it is too large Load Diff

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