eval(str [,globals [,locals ]])函數將字符串str當成有效Python表達式來求值,並返回計算結果。ide
一樣地, exec語句將字符串str當成有效Python代碼來執行.提供給exec的代碼的名稱空間和exec語句的名稱空間相同.函數
最後,execfile(filename [,globals [,locals ]])函數能夠用來執行一個文件,看下面的例子:spa
>>> eval('3+4') 對象
7 作用域
>>> exec 'a=100' 字符串
>>> a it
100 io
>>> execfile(r'c:\test.py') 編譯
hello,world! function
>>>
默認的,eval(),exec,execfile()所運行的代碼都位於當前的名字空間中. eval(), exec,和execfile()函數也能夠接受一個或兩個可選字典參數做爲代碼執行的全局名字空間和局部名字空間. 例如:
1 globals = {'x': 7,
2 'y': 10,
3 'birds': ['Parrot', 'Swallow', 'Albatross']
4 }
5 locals = { }
6
7 # 將上邊的字典做爲全局和局部名稱空間
8 a = eval("3*x + 4*y", globals, locals)
9 exec "for b in birds: print b" in globals, locals # 注意這裏的語法
10 execfile("foo.py", globals, locals)
若是你省略了一個或者兩個名稱空間參數,那麼當前的全局和局部名稱空間就被使用.若是一個函數體內嵌嵌套函數或lambda匿名函數時,同時又在函數主體中使用exec或execfile()函數時, 因爲牽到嵌套做用域,會引起一個SyntaxError異常.(此段原文:If you omit one or both namespaces, the current values of the global and local namespaces are used. Also,due to issues related to nested scopes, the use of exec or execfile() inside a function body may result in a SyntaxError exception if that function also contains nested function definitions or uses the lambda operator.)
在Python2.4中俺未發現能夠引發異常 注意例子中exec語句的用法和eval(), execfile()是不同的. exec是一個語句(就象print或while), 而eval()和execfile()則是內建函數. exec(str) 這種形式也被接受,可是它沒有返回值。 當一個字符串被exec,eval(),或execfile()執行時,解釋器會先將它們編譯爲字節代碼,而後再執行.這個過程比較耗時,因此若是須要對某段代碼執行不少次時,最好仍是對該代碼先進行預編譯,這樣就不須要每次都編譯一遍代碼,能夠有效提升程序的執行效率。 compile(str ,filename ,kind )函數將一個字符串編譯爲字節代碼, str是將要被編譯的字符串, filename是定義該字符串變量的文件,kind參數指定了代碼被編譯的類型-- 'single'指單個語句, 'exec'指多個語句, 'eval'指一個表達式. cmpile()函數返回一個代碼對象,該對象固然也能夠被傳遞給eval()函數和exec語句來執行,例如:
1 str = "for i in range(0,10): print i"
2 c = compile(str,'','exec') # 編譯爲字節代碼對象
3 exec c # 執行
4
5 str2 = "3*x + 4*y"
6 c2 = compile(str2, '', 'eval') # 編譯爲表達