Skip to content

Instantly share code, notes, and snippets.

@pdxjohnny
Created May 15, 2020 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdxjohnny/c58e03f92f87a9cba6e9370becf5f2c8 to your computer and use it in GitHub Desktop.
Save pdxjohnny/c58e03f92f87a9cba6e9370becf5f2c8 to your computer and use it in GitHub Desktop.
Untaring vs. using shutil.unpack_archive
import os
import shutil
import pathlib
import tempfile
import functools
import subprocess
import contextlib
import urllib.request
@contextlib.contextmanager
def chdir(new_path):
"""
Context manager to change directroy
"""
old_path = os.getcwd()
os.chdir(new_path)
try:
yield
finally:
os.chdir(old_path)
URL = "https://nodejs.org/dist/v14.2.0/node-v14.2.0-linux-x64.tar.xz"
with contextlib.ExitStack() as stack:
response = stack.enter_context(urllib.request.urlopen(URL))
tarfileobj = stack.enter_context(
tempfile.NamedTemporaryFile(suffix=".tar.xz", delete=False)
)
stack.callback(functools.partial(os.unlink, tarfileobj.name))
unpackdir = stack.enter_context(tempfile.TemporaryDirectory())
subtardir = stack.enter_context(tempfile.TemporaryDirectory())
tarfileobj.write(response.read())
tarfileobj.close()
with chdir(unpackdir):
shutil.unpack_archive(tarfileobj.name, ".")
with chdir(subtardir):
subprocess.call(["tar", "xJf", tarfileobj.name])
print("shutil.unpack_archive", len(list(pathlib.Path(unpackdir).rglob("*"))))
print("tar xJf", len(list(pathlib.Path(subtardir).rglob("*"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment