2011-11-22 42 views
3

我正在處理一些報告(計數),我必須爲不同的參數提取計數。非常簡單但乏味。是否可以在Python腳本中生成並執行Python代碼? [動態Python代碼]

一個參數查詢示例:

qCountsEmployee = (
    "select count(*) from %s where EmployeeName is not null" 
    % (tablename) 
    ) 
CountsEmployee = execute_query(qCountsEmployee) 

現在我有幾百個這樣的參數!

我所做的是:創建所有參數的列表,並使用快速Python腳本生成它們,然後複製文本,並把它在主腳本,避免了繁瑣的線條。

columnList = ['a', 'b', ............'zzzz'] 

for each in columnList: 
    print (
      'q' + each + ' =' 
      + '"select count(*) from %s where' + each 
      + 'is not null" % (tablename)' 
     ) 
    print each + ' = execute_query(' + 'q' + each + ')' 

雖然這種方法,我在想,如果不是一個單獨的腳本生成的代碼行,並複製粘貼到主程序,我可以在主腳本直接生成他們,讓腳本把它們作爲線的代碼?這將使我的代碼更具可讀性。希望我有道理!謝謝...

回答

5

這將是可能的,但在這裏是沒有用的。

只是不要像

columnList = ['a', 'b', ............'zzzz'] 

results = {} 
for column in columnList: 
    query = (
      "select count(*) from " + tablename 
      + " where " + column + " is not null" 
      ) 
    result = execute_query(qCountsEmployee) 
    results[column] = result 

你也可以把這個都聚集在一臺發電機的功能,做

def do_counting(column_list): 
    for column in column_list: 
     query = (
      "select count(*) from " + tablename 
      + " where " + column + " is not null" 
      ) 
     result = execute_query(qCountsEmployee) 
     yield column, result 

result_dict = dict(do_counting(['...'])) 
+0

你能解釋一下你的發電機解決方案嗎? – ThinkCode

+1

它遍歷給定列表的內容併爲每個項目產生一個2元組。這些2元組然後[放在一起dict](http://docs.python.org/library/stdtypes.html#dict)。 – glglgl

2

你可以這樣做:

 
cmd = compile('a = 5', '<string>', 'exec') 
exec(cmd) 

這是與剛纔寫的一樣:

 
a = 5 

如編譯可以動態建立的第一個參數傳遞的字符串。

+0

雖然我喜歡單行(或2),但將其應用到我的查詢和引用中有點令人困惑。將試着讓你知道它是否有效。謝謝! – ThinkCode

+1

繼續嘗試,但exec()是邪惡的。你應該像glglgl所建議的那樣編寫一個程序,在沒有動態代碼的情況下做你想做的事情。 – Dave

+0

謝謝,我拿你的執行是邪惡的建議! – ThinkCode

1

要建立在什麼glglgl說,你是使用動態SQL不是動態的Python(儘管動態的Python是絕對有可能使用像eval)可能會更好。在使用動態SQL時,你應該小心SQL注入。看起來它不會出現在你的特定用例中,但它肯定比許多開發人員意識到的要多得多。

我碰巧寫了一篇關於SQL Injection and Python的文章,它可在Simple-talk處獲得。