2014-04-30 52 views
1

在調用外部模塊Python函數我有將由遺傳算法中使用和 我希望能夠重複調用這些並監控結果蟒蛇功能和模塊手動維護的列表。通過串

test_exec.py

import os 
from random import randint 

def main(): 
    toolList = [{'file':'test1.py', 'function':'sum_even_numbers', 'args':['list'], 'return':['int']}, 
       {'file':'test1.py', 'function':'get_min_even_num', 'args':['list'], 'return':['int']} ] 
    for tool in toolList: 
     for i in range(0,3): 
      run(tool, [randint(10,99) for j in range(1,randint(2,5))]) 

def run(tool, args): 
    mod = __import__(os.path.basename(tool['file']).split('.')[0]) 
    func = getattr(mod, tool['function']) 
    tool['return'] = func(args) 
    print('main called ' + tool['file'] + '->' + tool['function'] + ' with ', args, ' = ', tool['return']) 

main() 

test1.py

def sum_even_numbers(numbers): 
    return sum([i for i in numbers if i % 2 == 0]) 

def get_min_even_num(numbers): 
    return min([i for i in numbers if i % 2 == 0]) 

# other code in test1.py which we dont want to execute 
print('test1.py has been run') 

結果代碼:

test1.py has been run 
('main called test1.py->sum_even_numbers with ', [30, 66, 25, 45], ' = ', 96) 
('main called test1.py->sum_even_numbers with ', [92], ' = ', 92) 
('main called test1.py->sum_even_numbers with ', [59, 73], ' = ', 0) 
('main called test1.py->get_min_even_num with ', [59, 12, 61, 24], ' = ', 12) 
('main called test1.py->get_min_even_num with ', [22], ' = ', 22) 
('main called test1.py->get_min_even_num with ', [97, 94], ' = ', 94) 

代碼工作,通過串調用模塊中的功能,但在導入過程中,這會執行整個文件。 有沒有更好的方法來做到這一點,使整個模塊不運行?

回答

4

當你從一個模塊導入某些東西 - 甚至是一個獨立的模塊級函數 - python解釋器解析/編譯整個文件,然後給你訪問該函數。

def S中的情況下,這是無害的 - 他們只是編成功能,又何妨呢。但是有時你有「你不想運行的代碼」,就像你的例子中的print

從當您導入模塊正在執行阻止代碼的典型方式是:

if __name__ == '__main__': 
    # code that only gets executed when I explicitly run this module 

More reading.

+1

而且,爲了使其更具體的,在這種情況下,很可能是'#代碼只會得到執行...'會是'main'的調用 - 例如'主()' – mgilson

+0

好了,如果整個文件始終加載並編譯我需要移動我的導入命令圈外,否則將被導入相同的模塊多次 – acutesoftware

+1

重新導入模塊不是很大應對。它只被編譯一次(第一次)。顯然,出於美觀的原因,最好只導入一次,但多次導入的性能影響非常小。 – roippi