主页 > Python函数 > 正文

python函数每日一讲 - exec履行函数

exec 函数功用:履行储存在字符串或文件中的 Python 句子,比较于 eval,exec可以履行更杂乱的 Python 代码。


英文解说

This function supports dynamic execution of Python code. object must be either a string 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 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 return and yield statements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.


In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.


If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().


留意: 在 Python2 中exec不是函数,而是一个内置句子(statement),可是Python 2中有一个 execfile() 函数。可以理解为 Python 3 把 exec 这个 statement 和 execfile() 函数的功用够整合到一个新的 exec() 函数中去了。

所以相似功用的函数在python2中是execfile。


适用版别

Python3.x


语法

以下是 exec 的语法:

exec(object[, globals[, locals]])


参数

object:必选参数,表明需求被指定的Python代码。它有必要是字符串或code目标。假如object是一个字符串,该字符串会先被解析为一组Python句子,然后在履行(除非发作语法错误)。假如object是一个code目标,那么它仅仅被简略的履行。

globals:可选参数,表明大局命名空间(寄存大局变量),假如被供给,则有必要是一个字典目标。

locals:可选参数,表明当时部分命名空间(寄存部分变量),假如被供给,可所以任何映射目标。假如该参数被疏忽,那么它将会取与globals相同的值。

返回值

exec 返回值永远为 None。

实例

>>>exec 'print "Hello Python"'
Hello Python
# 单行句子字符串
>>> exec "print 'vztug.com'"
vztug.com
 
#  多行句子字符串
>>> exec """for i in range(5):
...   print "iter time: %d" % i
... """
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4


上一篇:python函数每日一讲 - eval函数
下一篇:python函数每日一讲 - filter函数过滤序列

PythonTab微信大众号:

Python技能交流合作群 ( 请勿加多个群 ):

群1: 87464755

群2: 333646237

群3: 318130924

群4: 385100854