這個問題在這里已經有了答案: 動態從模塊匯入類 2答案 4天前關閉。
有一個 main 函式,它從多個檔案中呼叫函式。可能檔案已被洗掉,因此我想用 try except 塊包裝函式呼叫,并記錄執行函式所花費的時間。
我已經以次優的方式實作了這個,下面的代碼有效,有沒有更好的方法來做到這一點?
檔案
#main.py
#import time
def main():
timer_data = []
functions_to_be_called = []
a=time.time()
functions_to_be_called.append(("from side_branch_1 import side_branch_1","side_branch_1()"))
functions_to_be_called.append(("from side_branch_2 import side_branch", "side_branch()"))
call_function_safely(functions_to_be_called, timer_data)
b=time.time()
timer_data.append({'Func Name' : 'Overall','Time' : round(b - a,2)})
print(timer_data)
def call_function_safely(func_strings, timer_data):
for import_string, func_string in func_strings:
sub_a = time.time()
try:
exec(import_string)
exec(func_string)
except BaseException as error:
print(error)
sub_b = time.time()
timer_data.append({'Func Name' : 'side_branch_1','Time' : round(sub_b - sub_a,2)})
# side_branch_2.py
def side_branch():
print('side branch 2 called')
# side_branch_1.py
def side_branch_1():
print('Side Branch 1 Called')
return 'Side Branch 1'
uj5u.com熱心網友回復:
這沒有什么“安全”的。
無論如何,通過字串參考匯入模塊的更好方法是importlib.import_module
.
然后getattr
為要呼叫的函式名,然后呼叫它。
def call_by_name(module_name, func_name, *args, **kwargs):
try:
mod = importlib.import_module(module_name)
except ImportError:
return None
try:
func = getattr(mod, func_name)
except AttributeError:
return None
return func(*args, **kwargs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506849.html