Skip to content

Commit d9825d5

Browse files
authored
gh-160279: Keep the venv directory off the import path when running pip (#160282)
1 parent 0e35313 commit d9825d5

3 files changed

Lines changed: 12 additions & 3 deletions

File tree

‎Lib/test/test_venv.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1330,7 +1330,13 @@ def test_devnull(self):
13301330

13311331
def do_test_with_pip(self, system_site_packages):
13321332
rmtree(self.env_dir)
1333+
os.mkdir(self.env_dir)
1334+
# Both ensurepip and its pip subprocess run with the venv as cwd.
1335+
for name in ('ensurepip.py', 'subprocess.py'):
1336+
pathlib.Path(self.env_dir, name).write_text(
1337+
'raise AssertionError(__file__)\n', encoding='utf-8')
13331338
with EnvironmentVarGuard() as envvars:
1339+
envvars["PYTHONSAFEPATH"] = ""
13341340
# pip's cross-version compatibility may trigger deprecation
13351341
# warnings in current versions of Python. Ensure related
13361342
# environment settings don't cause venv to fail.

‎Lib/venv/__init__.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -446,14 +446,15 @@ def setup_python(self, context):
446446
def _call_new_python(self, context, *py_args, **kwargs):
447447
"""Executes the newly created Python using safe-ish options"""
448448
# gh-98251: We do not want to just use '-I' because that masks
449-
# legitimate user preferences (such as not writing bytecode). All we
450-
# really need is to ensure that the path variables do not overrule
451-
# normal venv handling.
449+
# legitimate user preferences (such as not writing bytecode).
452450
args = [context.env_exec_cmd, *py_args]
453451
kwargs['env'] = env = os.environ.copy()
454452
env['VIRTUAL_ENV'] = context.env_dir
455453
env.pop('PYTHONHOME', None)
456454
env.pop('PYTHONPATH', None)
455+
# Keep the working directory off sys.path, including in the
456+
# subprocess that ensurepip starts to run pip.
457+
env['PYTHONSAFEPATH'] = '1'
457458
kwargs['cwd'] = context.env_dir
458459
kwargs['executable'] = context.env_exec_cmd
459460
subprocess.check_output(args, **kwargs)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Prevent :mod:`venv` from importing modules from the root of an existing
2+
virtual environment when installing or upgrading pip.

0 commit comments

Comments
 (0)