6.14 exec 语句 The exec statement

exec_stmt  ::=  "exec" expression ["in" expression ["," expression]]
Download entire grammar as text.

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.

该语句支持Python 代码的动态执行。 第一个表达式应求值为一个字符串, 一个打开的文件对象, 或是一个代码对象. 如果它是字符串, 该字符串被分析为一组Python的语句,并随后运行 (除非发生语法错误)。如果是一打开的文件, 则分析该文件直到文件末尾,然后运行。如果是一代码对象,则简单地运行它。

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only the first expression after 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, both must be dictionaries and they are used for the global and local variables, respectively.

在所有情况下,如果省略了可选部分,代码就在当前的范围中运行。如果只给出了in 后面的表达式,它应为一个字典,并用于全局和局部的变量。如果给出了两个表达式, 两者都应是字典,且它们分别用于全局和局部变量。

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 __builtin__ under the key __builtins__ (!).

作为一种副作用,除了那些对应于由被执行代码所设置的变量的对象外,一种实现可能会向字典中加入额外的键。例如,当前的实现可能会向字典中加入__builtin__ 键名下的一个指向内建模块字典__builtin__ 的指针(!)。

Programmer's hints: dynamic evaluation of expressions is supported by the built-in function eval(). The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use by exec.

程序员提示: 表达式的动态执行由内建函数 eval() 支持。内建函数 globals() 和 locals() 分别返回当前的全局和局部字典,可用于传递给exec使用。