我是python开发的新手,我使用PYWB库重放网络档案(warc文件)。
我想在pywb/warcserver/index
中修改一个函数,但不修改代码源。
这个想法是在保留原始代码源的同时修改某些功能。在不丢失更改的情况下更新代码源将非常有用。
如何在python中使用python实现这一点。
indexsource.py
文件中重写的功能是load_index
由于
答案 0 :(得分:1)
load_index
是FileIndexSource
类的方法。您可以在实例级别修改方法,而无需更改库的源代码。例如:
from pywb.utils.binsearch import iter_range
from pywb.utils.wbexception import NotFoundException
from pywb.warcserver.index.cdxobject import CDXObject
from pywb.utils.format import res_template
def modified_load_index(self, params):
filename = res_template(self.filename_template, params)
try:
fh = open(filename, 'rb')
except IOError:
raise NotFoundException(filename)
def do_load(fh):
with fh:
gen = iter_range(fh, params['key'], params['end_key'])
for line in gen:
yield CDXObject(line)
# (... some modification on this method)
return do_load(fh)
# Change the "load_index" method on the instance of FileIndexSource
my_file_index_source.load_index = modified_load_index
接下来,每次在load_index
上调用方法my_file_index_source
时,它都将是将要运行的修改后的方法。
另一种选择是创建一个继承自FileIndexSource
的新类并覆盖load_index
方法。