2013-06-06 15 views
2

我需要動態生成python代碼並使用eval()函數執行它。在Python中評估動態生成的語句

我想要做的是產生一些「進口」和「分配值」。我的意思是,我需要生成這個字符串來評估它eval(x)

x = """ 
import testContextSummary 
import util.testGroupUtils 
testDb = [testContextSummary.TestContextSummary, 
      testGroupUtils.testGroupUtils.TestGroupUtils] 
""" # x is automatically generated 
eval(x) 
... use testDb ... 

我試着用這個代碼,但eval()函數返回不承認import一個錯誤,所以我想這個代碼。

x = """ 
testContextSummary = __import__("testContextSummary") 
testGroupUtils = __import__("util.testGroupUtils") 
testDb = [testContextSummary.TestContextSummary, 
      testGroupUtils.testGroupUtils.TestGroupUtils] 
""" # x is automatically generated 

eval(x) # error 

我再次得到一個錯誤,不允許賦值語句。

有什麼辦法可以執行動態生成的python腳本,並使用評估結果?

回答

2

您想要exec而不是eval

>>> s = "x = 2" 
>>> exec s 
>>> x 
2 

當然,請不要使用exec上不可信串...

+0

prosseek:這是因爲'EXEC()'可以處理多行的Python,而'eval()'只評估一個表達式。注意安全。 – martineau

+0

@martineau:我沒有看到原來的評論,但是'exec'同樣適用於'eval',它與多行代碼無關...('__import __('os'))。 remove('important_file')') – mgilson

0

這也可能工作:

x = """[ 
     __import__("testContextSummary").TestContextSummary, 
     __import__("util.testGroupUtils").testGroupUtils.TestGroupUtils] 
""" 
testDB=eval(x) 
+0

雖然這可能適用於這種特殊情況,但如果定義了多個名稱或動態生成的代碼中存在更復雜的邏輯,比如'if/else'構造和/或函數/類定義等 - 所有'exec()'應該能夠處理。 – martineau