diff --git a/Lib/test/test_venv.py b/Lib/test/test_venv.py index 0c6cd1b196ac812..7cb3062ed85e5cb 100644 --- a/Lib/test/test_venv.py +++ b/Lib/test/test_venv.py @@ -1008,6 +1008,23 @@ def test_devnull(self): self.assertTrue(os.path.exists(os.devnull)) + def test_ensurepip_failure_shows_stderr(self): + """Test that ensurepip failure output is shown to the user (gh-89830)""" + with tempfile.TemporaryDirectory() as env_dir: + builder = venv.EnvBuilder(with_pip=True) + # Simulate ensurepip failing with a traceback on stderr + def fake_call_new_python(context, *args, **kwargs): + raise subprocess.CalledProcessError( + returncode=1, + cmd=args, + stderr=b"AttributeError: simulated ensurepip failure" + ) + with patch.object(venv.EnvBuilder, '_call_new_python', fake_call_new_python): + with captured_stderr() as err: + with self.assertRaises(subprocess.CalledProcessError): + builder.create(env_dir) + self.assertIn("simulated ensurepip failure", err.getvalue()) + def do_test_with_pip(self, system_site_packages): rmtree(self.env_dir) with EnvironmentVarGuard() as envvars: diff --git a/Lib/venv/__init__.py b/Lib/venv/__init__.py index bd2762d55ef6961..e2ec7a9ae1d6cc6 100644 --- a/Lib/venv/__init__.py +++ b/Lib/venv/__init__.py @@ -459,8 +459,13 @@ def _call_new_python(self, context, *py_args, **kwargs): def _setup_pip(self, context): """Installs or upgrades pip in a virtual environment""" - self._call_new_python(context, '-m', 'ensurepip', '--upgrade', - '--default-pip', stderr=subprocess.STDOUT) + try: + self._call_new_python(context, '-m', 'ensurepip', '--upgrade', + '--default-pip', stderr=subprocess.PIPE) + except subprocess.CalledProcessError as e: + if e.stderr: + print(e.stderr.decode(errors='replace'), file=sys.stderr) + raise def setup_scripts(self, context): """ diff --git a/Misc/NEWS.d/next/Library/2026-06-10-19-00-53.gh-issue-89830.YGHExb.rst b/Misc/NEWS.d/next/Library/2026-06-10-19-00-53.gh-issue-89830.YGHExb.rst new file mode 100644 index 000000000000000..3e2ece090db8ca0 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-06-10-19-00-53.gh-issue-89830.YGHExb.rst @@ -0,0 +1,2 @@ +Fix unhelpful error message when :mod:`venv` fails to install pip via +:mod:`ensurepip` by displaying the subprocess stderr output.