From 0cec14ff91464fbd64ec4dd6d347b5295388c471 Mon Sep 17 00:00:00 2001 From: Jonathon Reinhart Date: Sun, 14 Jan 2024 00:16:06 -0500 Subject: [PATCH] staticx: Use importlib.resources over pkg_resources for asset access pkg_resources is deprecated: https://setuptools.pypa.io/en/latest/pkg_resources.html This prefers importlib.metadata (introduced in Python 3.8) and uses the backport importlib_metadata for Python 3.7 (to be removed in #264). This instead uses importlib.resources.files() (introduced in Python 3.9) and uses the backport importlib_resources for Python 3.7-3.8 (to be removed in #264, #265). This was chosen over the alternative of using the deprecated (as of Python 3.11) function importlib.resources.open_binary() (introduced in Python 3.7), as it seems simpler. --- pyproject.toml | 2 ++ staticx/assets.py | 12 ++++++++++-- staticx/version.py | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 339b6ca..4ed239d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,8 @@ dependencies = [ "pyelftools", # TODO(#264): Remove when Python 3.7 support is removed. "importlib_metadata; python_version<'3.8'", + # TODO(#265): Remove when Python 3.8 support is removed. + "importlib_resources; python_version<'3.9'", ] description = "Build static self-extracting app from dynamic executable" license = {file = "LICENSE.txt"} diff --git a/staticx/assets.py b/staticx/assets.py index e275c1f..76f0576 100644 --- a/staticx/assets.py +++ b/staticx/assets.py @@ -1,11 +1,19 @@ -import pkg_resources +import sys from .utils import copy_fileobj_to_tempfile +# TODO(#265): Remove backport when Python 3.8 support is removed. +# importlib.resources.files() was added in Python 3.9. +if sys.version_info >= (3, 9): + import importlib.resources as importlib_resources +else: + import importlib_resources # backport + + def locate_asset(name, debug): mode = 'debug' if debug else 'release' path = '/'.join(('assets', mode, name)) try: - return pkg_resources.resource_stream(__name__, path) + return importlib_resources.files("staticx").joinpath(path).open("rb") except FileNotFoundError: raise KeyError(f"Asset not found: {name!r} (mode={mode!r})") diff --git a/staticx/version.py b/staticx/version.py index a2807fd..8abf568 100644 --- a/staticx/version.py +++ b/staticx/version.py @@ -62,7 +62,7 @@ def get_version(): # Otherwise, we're either installed (e.g. via pip), or running from # an 'sdist' source distribution, and have a local PKG_INFO file. - # TODO(#242): Remove backport when Python 3.7 support is removed. + # TODO(#264): Remove backport when Python 3.7 support is removed. if sys.version_info >= (3, 8): import importlib.metadata as importlib_metadata else: