[英]Calling Python functions in external modules by string
我有一個遺傳算法將使用的手動維護的python函數和模塊列表,我希望能夠重復調用它們並監視結果。
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()
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)
該代碼通過按字符串調用模塊中的函數而起作用,但是在導入過程中,它將執行整個文件。 有沒有更好的方法可以做到這一點,以使整個模塊都不會運行?
當您從模塊(甚至是獨立的模塊級函數)中導入某些內容時,python解釋器必須先解析/編譯整個文件,然后才能訪問該函數。
在def
的情況下,這是無害的-它們只是編譯成函數,不會造成傷害。 但是有時您會遇到“您不想運行的代碼”,例如示例中的print
。
導入模塊時,阻止代碼執行的規范方法是:
if __name__ == '__main__':
# code that only gets executed when I explicitly run this module
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.