標籤:元組 strong list 對象 應用 blog 執行 div 使用
eval(source[, globals[, locals]])
作用:
將字串str當成有效運算式來求值並返回計算結果。參數:source:一個Python運算式或函數compile()返回的代碼對象;globals:可選。必須是dictionary;locals:可選。任意map對象。
執行個體:
1 ################################################# 2 字串轉換成列表 3 >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" 4 >>>type(a) 5 <type ‘str‘> 6 >>> b = eval(a) 7 >>> print b 8 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]] 9 >>> type(b)10 <type ‘list‘>11 #################################################12 字串轉換成字典13 >>> a = "{1: ‘a‘, 2: ‘b‘}"14 >>> type(a)15 <type ‘str‘>16 >>> b = eval(a)17 >>> print b18 {1: ‘a‘, 2: ‘b‘}19 >>> type(b)20 <type ‘dict‘>21 #################################################22 字串轉換成元組23 >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"24 >>> type(a)25 <type ‘str‘>26 >>> b = eval(a)27 >>> print b28 ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))29 >>> type(b)30 <type ‘tuple‘>
1 #test eval() and locals() 2 x = 1 3 y = 1 4 num1 = eval("x+y") 5 print (num1) 6 7 def g(): 8 x = 2 9 y = 2 10 num3 = eval("x+y") 11 print (num3) 12 num2 = eval("x+y",globals()) 13 #num2 = eval("x+y",globals(),locals()) 14 print (num2)15 16 g()17 18 print locals()["x"]19 print locals()["y"] 20 print globals()["x"]21 print globals()["y"]
num1的值是2;num3的值也很好理解,是4;num2的值呢?由於提供了globals()參數,那麼首先應當找全域的x和y值,也就是都為1,那麼顯而易見,num2的值也是2。如果注釋掉該句,執行下面一句呢?根據第3)點可知,結果為4
eval()使用原因:
1)在編譯語言裡要動態地產生代碼,基本上是不可能的,但動態語言是可以,意味著軟體已經部署到伺服器上了,但只要作很少的更改,只好直接修改這部分的代碼,就可立即實現變化,不用整個軟體重新載入。
2)在machin learning雷根據使用者使用這個軟體頻率,以及方式,可動態地修改代碼,適應使用者的變化。
註:
eval有安全性問題,比如使用者惡意輸入就會獲得目前的目錄檔案
1 eval("__import__(‘os‘).system(‘dir‘)")
1 >>> import os2 >>> ‘os‘ in globals()3 True4 >>> os.system(‘whoami‘)5 ap\zhail
怎麼避免安全問題?
1、自行寫檢查函數;
2、使用ast.literal_eval
Python函數-eval()