Python函數-eval()

來源:互聯網
上載者:User

標籤:元組   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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.