Skip to content

Commit c32b185

Browse files
committed
Remove virtualenv site-packages from sys.path in context manager exit
Fixes #34 Signed-off-by: Pedro Algarvio <[email protected]>
1 parent b129cfb commit c32b185

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

changelog/34.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Remove virtualenv `site-packages` from `sys.path` in context manager exit

src/ptscripts/virtualenv.py

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import os
77
import pathlib
88
import shutil
9-
import site
109
import subprocess
1110
import sys
1211
import textwrap
@@ -193,11 +192,26 @@ def _add_as_extra_site_packages(self):
193192
f"Failed to get the virtualenv's site packages path: {ret.stderr.decode()}"
194193
)
195194
self.ctx.exit(1)
196-
site_packages = site.getsitepackages()
197195
for path in json.loads(ret.stdout.strip().decode()):
198-
if path not in site_packages:
199-
site.addsitedir(path)
200-
site_packages = site.getsitepackages()
196+
if path not in sys.path:
197+
sys.path.append(path)
198+
199+
def _remove_extra_site_packages(self):
200+
if self.add_as_extra_site_packages is False:
201+
return
202+
ret = self.run_code(
203+
"import json,site; print(json.dumps(site.getsitepackages()))",
204+
capture=True,
205+
check=False,
206+
)
207+
if ret.returncode:
208+
self.ctx.error(
209+
f"Failed to get the virtualenv's site packages path: {ret.stderr.decode()}"
210+
)
211+
self.ctx.exit(1)
212+
for path in json.loads(ret.stdout.strip().decode()):
213+
if path in sys.path:
214+
sys.path.remove(path)
201215

202216
def __enter__(self):
203217
"""
@@ -215,6 +229,7 @@ def __exit__(self, *args):
215229
"""
216230
Exit the virtual environment context.
217231
"""
232+
self._remove_extra_site_packages()
218233

219234
def install(self, *args, **kwargs):
220235
"""

0 commit comments

Comments
 (0)