如何在python模块中挂钩函数? [英] How can I hook a function in a python module?
问题描述
因此,我在虚拟环境中的程序包安装在它的site-packages文件夹中. 在该程序包中,有一个带有一堆功能的模块,我想更改其中一个功能而不接触程序包代码,所以我想对该模块做一个钩子,然后更改/覆盖该功能,使其表现为我想要.
So I have a package in my virtual environment installed in the site-packages folder of it. In that package there is a module with a bunch of functions, I want to change one of these functions without touching the package code, so I want to make a hook of that module and then change/overwrite the function so it behaves in the way I want.
我不知道这在python中是否可行(我是该语言的新手)
I don't know if this is even posible in python (I'm new to the language)
示例:
我的site-packages文件夹中有一个名为them_package的软件包,内部有一个名为what.py的模块,其代码如下:
I have a package called their_package in my site-packages folder, inside I have a module named whatever.py with the following code:
import sys
import os
def this_is_a_function(parameter):
//whatever logic in here
return result
我想要的是钩住what.py模块,以便我可以重新定义this_is_a_function以具有不同的逻辑.这可以吗?我将不胜感激一个代码示例!
What I want is to hook the whatever.py module so I can redefine the this_is_a_function to have a diferent logic. Is this posible? I would appreciate a lot a code sample!
提前谢谢!:)
推荐答案
您可以使用以下方法重新定义函数:
You can redefine your function with:
import whatever
def this_is_a_function(parameter):
pass
whatever.this_is_a_function = this_is_a_function
这篇关于如何在python模块中挂钩函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!