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)
代碼工作,通過串調用模塊中的功能,但在導入過程中,這會執行整個文件。 有沒有更好的方法來做到這一點,使整個模塊不運行?
而且,爲了使其更具體的,在這種情況下,很可能是'#代碼只會得到執行...'會是'main'的調用 - 例如'主()' – mgilson
好了,如果整個文件始終加載並編譯我需要移動我的導入命令圈外,否則將被導入相同的模塊多次 – acutesoftware
重新導入模塊不是很大應對。它只被編譯一次(第一次)。顯然,出於美觀的原因,最好只導入一次,但多次導入的性能影響非常小。 – roippi