Created
May 15, 2020 21:21
-
-
Save pdxjohnny/c58e03f92f87a9cba6e9370becf5f2c8 to your computer and use it in GitHub Desktop.
Untaring vs. using shutil.unpack_archive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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