Skip to content

Commit f32c795

Browse files
authored
bpo-43650: Fix MemoryError on zip.read in shutil._unpack_zipfile for large files (pythonGH-25058)
`shutil.unpack_archive()` tries to read the whole file into memory, making no use of any kind of smaller buffer. Process crashes for really large files: I.e. archive: ~1.7G, unpacked: ~10G. Before the crash it can easily take away all available RAM on smaller systems. Had to pull the code form `zipfile.Zipfile.extractall()` to fix this Automerge-Triggered-By: GH:gpshead
1 parent 83f0f8d commit f32c795

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

Lib/shutil.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,20 +1163,16 @@ def _unpack_zipfile(filename, extract_dir):
11631163
if name.startswith('/') or '..' in name:
11641164
continue
11651165

1166-
target = os.path.join(extract_dir, *name.split('/'))
1167-
if not target:
1166+
targetpath = os.path.join(extract_dir, *name.split('/'))
1167+
if not targetpath:
11681168
continue
11691169

1170-
_ensure_directory(target)
1170+
_ensure_directory(targetpath)
11711171
if not name.endswith('/'):
11721172
# file
1173-
data = zip.read(info.filename)
1174-
f = open(target, 'wb')
1175-
try:
1176-
f.write(data)
1177-
finally:
1178-
f.close()
1179-
del data
1173+
with zip.open(name, 'r') as source, \
1174+
open(targetpath, 'wb') as target:
1175+
copyfileobj(source, target)
11801176
finally:
11811177
zip.close()
11821178

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :exc:`MemoryError` in :func:`shutil.unpack_archive` which fails inside
2+
:func:`shutil._unpack_zipfile` on large files. Patch by Igor Bolshakov.

0 commit comments

Comments
 (0)