我是在 Numpy 模块上做的,所以你应该可以对任何模块使用相同的方法:
import numpy as np # import the module you want to be logged
from inspect import getmembers, isfunction # These will give us the functions in a module
import time # for logging the time
class Object(object): # make a dummy class on which we can do "setattr()"
pass
numpy_with_time_logger = Object() # We are going to make numpy_with_time_logger work exactly like Numpy except that it will also print start and end times
def return_call_time_logger(f): # This function takes in a function and returns a new function!
def call_time_logger(*args, **kargs): # This function is going to substitute f. It runs f(), but it also prints the times.
print(f'Function call started at {time.time()}')
ret_val = f(*args, **kargs)
print(f'Function call ended at {time.time()}')
return ret_val
return call_time_logger
for f_name, f in getmembers(numpy, isfunction): # For every function inside numpy module
# Set numpy_with_time_logger.f_name to be return_call_time_logger(f)
setattr(numpy_with_time_logger, f_name, return_call_time_logger(f))
注意:要使其适用于您自己的模块,只需将getmembers(numpy, isfunction) 中的“numpy”更改为您导入的模块的名称即可。
现在,我们的 numpy_with_time_logger 对象设置为与 Numpy 完全相同,但它也会打印开始和结束时间。所以尝试通过 numpy_with_time_logger 使用任何 numpy 的函数:
print(numpy_with_time_logger.asarray([1,2]))
输出是:
start time 1615096471.112301
end time 1615096471.1134446
array([1, 2])
这个方法的一个问题:
如果你调用numpy_with_time_logger.func1()和numpy_with_time_logger.func1()调用numpy.func2(),那么你只会得到func1的时间日志,你不会得到func2的时间日志。
要访问 Numpy 模块中定义的全局变量,只需继续使用 numpy,例如numpy.int32.