Python使用eval函數(shù)執(zhí)行動態(tài)標表達式過程詳解
英文文檔:
eval(expression, globals=None, locals=None)
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, localscan be any mapping object.
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and lacks ‘__builtins__', the current globals are copied into globals before expression is parsed. This means that expressionnormally has full access to the standard builtins module and restricted environments are propagated. If the localsdictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>> x = 1
>>> eval('x+1')
2
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()‘s return value will be None.
Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().
See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.
執(zhí)行動態(tài)標表達式求值
說明:
1. 執(zhí)行動態(tài)語句,返回語句執(zhí)行的值。
>>> eval('1+2+3+4')
10
2. 第一個參數(shù)為語句字符串,globals參數(shù)和locals參數(shù)為可選參數(shù),如果提供,globals參數(shù)必需是字典,locals參數(shù)為mapping對象。
3. globals參數(shù)用來指定代碼執(zhí)行時可以使用的全局變量以及收集代碼執(zhí)行后的全局變量。
>>> g = {'num':2} >>> eval('num + 2') #num未定義 Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> eval('num + 2') File "<string>", line 1, in <module> NameError: name 'num' is not defined >>> eval('num + 2',g) #g中有定義num,可執(zhí)行 4
4. locals參數(shù)用來指定代碼執(zhí)行時可以使用的局部變量以及收集代碼執(zhí)行后的局部變量
>>> g = {'num1':2} >>> l = {'num2':4} >>> eval('num1+num2',g,l) 6
5. 為了保證代碼成功運行,globals參數(shù)字典不包含 __builtins__ 這個 key 時,Python會自動添加一個key為 __builtins__ ,value為builtins模塊的引用。如果確實要限制代碼不使用builtins模塊,需要在global添加一個key為__builtins__,value為{}的項即可(很少有人這么干吧)。
>>> g = {} >>> eval('abs(-1)',g) 1 >>> g = {'__builtins__':{}} >>> eval('abs(-1)',g) #不能使用內(nèi)置函數(shù)了 Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> eval('abs(-1)',g) File "<string>", line 1, in <module> NameError: name 'abs' is not defined
6. 當globals參數(shù)不提供是,Python默認使用globals()函數(shù)返回的字典去調(diào)用。當locals參數(shù)不提供時,默認使用globals參數(shù)去調(diào)用。
>>> num = 1 >>> eval('num+2') 3 >>> globals() #返回字典中含有num的key {'__doc__': None, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>} >>> eval('num+2',{}) #locals參數(shù)未提供,locals參數(shù)=globals參數(shù) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> eval('num+2',{}) File "<string>", line 1, in <module> NameError: name 'num' is not defined >>> l = locals() >>> eval('num+2',{},l) #locals參數(shù)含有num的key,能求值 3 >>> locals() {'__doc__': None, 'l': {...}, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>} >>>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python異步實現(xiàn)定時任務(wù)和周期任務(wù)的方法
今天小編就為大家分享一篇python異步實現(xiàn)定時任務(wù)和周期任務(wù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python從入門到精通之條件語句和循環(huán)結(jié)構(gòu)詳解
Python中提供了強大而靈活的條件語句和循環(huán)結(jié)構(gòu),本文將從入門到精通地介紹它們的使用方法,并通過相關(guān)代碼進行講解,希望對大家深入了解Python有一定的幫助2023-07-07urllib和BeautifulSoup爬取維基百科的詞條簡單實例
這篇文章主要介紹了urllib和BeautifulSoup爬取維基百科的詞條簡單實例,具有一定借鑒價值,需要的朋友可以參考下2018-01-01給大家整理了19個pythonic的編程習慣(小結(jié))
這篇文章主要介紹了給大家整理了19個pythonic的編程習慣(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09Python?Pexpect庫自動化交互式進程控制的expect_list方法解析
Pexpect是一個Python庫,為自動化和交互式進程控制提供了豐富的功能,而expect_list方法是其功能強大且靈活的一部分,將詳細探討如何使用這一方法,并提供多個示例來說明其應(yīng)用場景和功能2024-01-01