所以我试图对shutil模块进行monkeypatch,以便对他们的make_archive函数使用最近的修复,允许创建大型zip文件。
我证明了一些概念,所以想到一个快速的黑客来解决这个问题会让我继续我想做的事情。
我的代码:
import shutil
import os
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
zip_filename = base_name + ".zip"
archive_dir = os.path.dirname(base_name)
if not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# If zipfile module is not available, try spawning an external 'zip'
# command.
try:
import zipfile
except ImportError:
zipfile = None
if zipfile is None:
shutil._call_external_zip(base_dir, zip_filename, verbose, dry_run)
else:
if logger is not None:
logger.info("creating '%s' and adding '%s' to it",
zip_filename, base_dir)
if not dry_run:
zip = zipfile.ZipFile(zip_filename, "w",
compression=zipfile.ZIP_DEFLATED,
allowZip64=True) # this is the extra argument
for dirpath, dirnames, filenames in os.walk(base_dir):
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
zip.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
zip.close()
shutil._make_zipfile = _make_zipfile
# This function calls _make_zipfile when it runs
shutil.make_archive('blah', someargs)
所以问题是......它没有做任何事情。我显然做了一些愚蠢的事,但对于我的生活,我看不出它是什么。我假设有一些显而易见的事情,我看了很长时间后都变得盲目,所以需要一些新鲜的眼睛。我尝试了以下方法/检查这些中描述的答案:
Monkey-patch Python class Python monkey patch private function 和What is a monkey patch?
加上其他一些。没有快乐
答案 0 :(得分:5)
您必须更新_ARCHIVE_FORMATS
映射;它会在导入时存储对该函数的引用,因此在您对其进行修补之前。 shutil.make_archive()
使用该映射,而不是直接使用_make_zipfile
函数。
您可以使用公开shutil.register_archive_format()
function重新定义zip
存档:
shutil.register_archive_format('zip', _make_zipfile, description='ZIP file')
这将替换为zip
格式注册的现有callable。