Skip to content

Commit 115c9c2

Browse files
committed
fix #32
1 parent 5a3d153 commit 115c9c2

File tree

3 files changed

+14
-15
lines changed

3 files changed

+14
-15
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ So, what could `zipapps` be?
7878
## 4. Activate the `.pyz` environment
7979

8080
1. use `zipimport` (Recommended)
81-
1. `zipimport.zipimporter("some_lib_venv.pyz").find_spec("ensure_zipapps").loader.load_module("ensure_zipapps")`
81+
1. `sys.path.append("some_lib_venv.pyz");importlib.import_module("ensure_zipapps")`
8282
2. automatically unzip cache, and add the path to sys.path
8383
1. it can be run multiple times
8484
2. if they are all pure-python code and **no need to decompress**

test_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -404,12 +404,12 @@ def test_unzip_with_auto_unzip():
404404

405405
def test_env_usage():
406406
# test ensure path for venv usage
407+
import importlib
407408
_clean_paths(root=False)
408409
create_app(output="bottle_env.pyz", unzip="bottle", pip_args=["bottle"])
409410
# activate sys.path and unzip cache
410-
spec = zipimport.zipimporter("bottle_env.pyz").find_spec("ensure_zipapps")
411-
if spec and spec.loader:
412-
spec.loader.load_module("ensure_zipapps")
411+
sys.path.append("bottle_env.pyz")
412+
importlib.import_module("ensure_zipapps")
413413
import bottle
414414

415415
# using app unzip cache for `import ensure_zipapps`

zipapps/activate_zipapps.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
1+
import importlib
2+
import sys
13
import zipfile
2-
import zipimport
34
from pathlib import Path
4-
from sys import modules, stderr
55

66

77
def activate(path=None):
88
path = Path(path) if path else Path(__file__).parent
99
path_str = path.absolute().as_posix()
1010
if zipfile.is_zipfile(path_str):
1111
try:
12-
spec = zipimport.zipimporter(path_str).find_spec("ensure_zipapps")
13-
if spec and spec.loader:
14-
_tmp = spec.loader.load_module("ensure_zipapps")
15-
modules.pop(_tmp.__name__, None)
16-
del _tmp
17-
return True
18-
else:
19-
raise ImportError(path_str)
12+
sys.path.insert(0, path_str)
13+
ensure_zipapps = importlib.import_module("ensure_zipapps")
14+
del ensure_zipapps
15+
sys.modules.pop("ensure_zipapps", None)
2016
except ImportError as err:
21-
stderr.write(f"WARNING: activate failed for {err!r}\n")
17+
sys.stderr.write(f"WARNING: activate failed for {err!r}\n")
2218
raise err
19+
finally:
20+
if sys.path[0] == path_str:
21+
sys.path.pop(0)

0 commit comments

Comments
 (0)