From 6c2690e4af5e12d68a5b91f7c9117f783e528277 Mon Sep 17 00:00:00 2001 From: pranavrajpal <78008260+pranavrajpal@users.noreply.github.com> Date: Thu, 19 May 2022 08:04:06 -0700 Subject: [PATCH] Avoid crashing on invalid python executables (#12812) When an invalid python executable is passed to mypy, show an error message instead of crashing. --- mypy/modulefinder.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/mypy/modulefinder.py b/mypy/modulefinder.py index bee99156a570..4ab95dd6564f 100644 --- a/mypy/modulefinder.py +++ b/mypy/modulefinder.py @@ -12,6 +12,8 @@ import sys from enum import Enum, unique +from mypy.errors import CompileError + if sys.version_info >= (3, 11): import tomllib else: @@ -649,9 +651,15 @@ def get_site_packages_dirs(python_executable: Optional[str]) -> Tuple[List[str], else: # Use subprocess to get the package directory of given Python # executable - site_packages = ast.literal_eval( - subprocess.check_output([python_executable, pyinfo.__file__, 'getsitepackages'], - stderr=subprocess.PIPE).decode()) + try: + site_packages = ast.literal_eval( + subprocess.check_output([python_executable, pyinfo.__file__, 'getsitepackages'], + stderr=subprocess.PIPE).decode()) + except OSError as err: + reason = os.strerror(err.errno) + raise CompileError( + [f"mypy: Invalid python executable '{python_executable}': {reason}"] + ) from err return expand_site_packages(site_packages)