python函式每日一講 - exec執行函式

pythontab發表於2018-03-19

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 'pythontab.com'"
pythontab.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


相關文章