Skip to content

Commit a8bde57

Browse files
committed
update zipimporter of activate_zipapps.py
1 parent 5e3ba4c commit a8bde57

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
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. `sys.path.append("some_lib_venv.pyz");importlib.import_module("ensure_zipapps")`
81+
1. `sys.path.insert(0, "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**

zipapps/activate_zipapps.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import zipimport
21
import sys
32
import zipfile
43
from pathlib import Path
@@ -9,14 +8,19 @@ def activate(path=None):
98
path_str = path.absolute().as_posix()
109
if zipfile.is_zipfile(path_str):
1110
try:
12-
importer = zipimport.zipimporter(path_str)
13-
spec = importer.find_spec("ensure_zipapps")
14-
if spec and spec.loader is not None:
15-
ensure_zipapps = spec.loader.load_module("ensure_zipapps")
16-
del ensure_zipapps
17-
sys.modules.pop("ensure_zipapps", None)
18-
else:
19-
raise ImportError(f"Cannot find 'ensure_zipapps' in {path_str!r}")
11+
from zipimport import zipimporter
12+
13+
importer = zipimporter(path_str)
14+
try:
15+
spec = importer.find_spec("ensure_zipapps") # 返回ModuleSpec
16+
if spec and spec.loader:
17+
module = spec.loader.load_module("ensure_zipapps") # 直接加载
18+
else:
19+
raise ImportError("Module not found")
20+
except AttributeError:
21+
module = importer.load_module("ensure_zipapps")
22+
del module
23+
sys.modules.pop("ensure_zipapps", None)
2024
except ImportError as err:
2125
sys.stderr.write(f"WARNING: activate failed for {err!r}\n")
2226
raise err

0 commit comments

Comments
 (0)