首页 > 解决方案 > 补丁模块进入和退出 - Python

问题描述

我有一个名为 my_module 的模块,我想测量它的性能。

my_module有多个功能,我想做的是,每当调用模块中的任何功能时

所以假设我运行了这个 -my_module.func('blah')

我想打印

对于模块中的任何功能。

我不能对模块文件进行任何直接更改,因为它也必须在其他地方使用。我只需要这个来打印性能测试脚本。

请帮忙。

标签: pythonpython-3.xmockingmonkeypatching

解决方案


我是在 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))

注意:要使其适用于您自己的模块,只需将“numpy”更改getmembers(numpy, isfunction)为您导入模块的名称。

现在,我们的 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.


推荐阅读