Skip to content

Commit

Permalink
Raise a rich error when venv can't be imported
Browse files Browse the repository at this point in the history
  • Loading branch information
pradyunsg committed Dec 11, 2022
1 parent f4cedb2 commit 3bb5d5e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/pip/_internal/build_env/_venv.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

import os
import sys
import venv
from types import TracebackType
from typing import TYPE_CHECKING, Dict, Iterable, Optional, Type

from pip._vendor.requests.certs import where

from pip._internal.cli.spinners import open_spinner
from pip._internal.exceptions import VenvImportError
from pip._internal.utils.subprocess import call_subprocess
from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds

Expand All @@ -23,6 +23,13 @@ class VenvBuildEnvironment(BuildEnvironment):
"""A build environment that does nothing."""

def __init__(self) -> None:
# We defer this import because certain redistributors (like Debian) have decided
# that parts of the Python standard library should not be shipped with Python.
try:
import venv
except ImportError:
raise VenvImportError()

self._temp_dir = TempDirectory(
kind=tempdir_kinds.BUILD_ENV, globally_managed=True
)
Expand Down
33 changes: 33 additions & 0 deletions src/pip/_internal/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@

import configparser
import re
import sys
from itertools import chain, groupby, repeat
from typing import TYPE_CHECKING, Dict, List, Optional, Union

from pip._vendor import distro
from pip._vendor.requests.models import Request, Response
from pip._vendor.rich.console import Console, ConsoleOptions, RenderResult
from pip._vendor.rich.markup import escape
Expand Down Expand Up @@ -169,6 +171,37 @@ def __rich_console__(
#
# Actual Errors
#
class VenvImportError(DiagnosticPipError):
"""Raised when `venv` can't be imported."""

reference = "venv-importerror"

def __init__(self) -> None:
if sys.platform != "linux":
hint_stmt = None
elif distro.like() == "debian":
hint_stmt = (
"Debian has split the Python standard library into multiple "
"pieces and maintains the venv as a separate `python3-venv` (or "
"`python3.x-venv`) package."
)
else:
hint_stmt = (
"If this is an OS-provided Python, it's likely that your OS "
"package maintainers have split Python's standard library across "
"multiple OS packages."
)
super().__init__(
message="Can not import the `venv` module of the Python standard library",
context=(
"This is a symptom of a broken/modified Python, which cannot be used "
"with pip."
),
note_stmt="This is an issue with the Python installation itself, not pip.",
hint_stmt=hint_stmt,
)


class ConfigurationError(PipError):
"""General exception in configuration"""

Expand Down

0 comments on commit 3bb5d5e

Please sign in to comment.