Skip to content

Commit

Permalink
15110: set env var for subprocess, check version in script (#15122)
Browse files Browse the repository at this point in the history
Fixes #15110 

- Add PYTHONSAFEPATH="true" to call to subprocess in get_search_dirs()
- Check sys.version_info before modifying path in pyinfo.py 

To test, import mypy.modulefinder.get_search_dirs & run:
- get_search_dirs() with no args
- on Python 3.11, call get_search_dirs with an earlier version as
python_executable
- on Python < 3.11, call get_search_dirs with Python 3.11 as
python_executable

Expected:
- consistent results, no exceptions

Co-authored-by: eevel <eevel@weezel3.weezelnet>
Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
  • Loading branch information
4 people committed Apr 25, 2023
1 parent e4217f2 commit 0dafc47
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
9 changes: 8 additions & 1 deletion mypy/modulefinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -751,12 +751,19 @@ def get_search_dirs(python_executable: str | None) -> tuple[list[str], list[str]
else:
# Use subprocess to get the package directory of given Python
# executable
env = {**dict(os.environ), "PYTHONSAFEPATH": "1"}
try:
sys_path, site_packages = ast.literal_eval(
subprocess.check_output(
[python_executable, pyinfo.__file__, "getsearchdirs"], stderr=subprocess.PIPE
[python_executable, pyinfo.__file__, "getsearchdirs"],
env=env,
stderr=subprocess.PIPE,
).decode()
)
except subprocess.CalledProcessError as err:
print(err.stderr)
print(err.stdout)
raise
except OSError as err:
reason = os.strerror(err.errno)
raise CompileError(
Expand Down
11 changes: 6 additions & 5 deletions mypy/pyinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
if __name__ == "__main__":
# HACK: We don't want to pick up mypy.types as the top-level types
# module. This could happen if this file is run as a script.
# This workaround fixes it.
old_sys_path = sys.path
sys.path = sys.path[1:]
import types # noqa: F401
# This workaround fixes this for Python versions before 3.11.
if sys.version_info < (3, 11):
old_sys_path = sys.path
sys.path = sys.path[1:]
import types # noqa: F401

sys.path = old_sys_path
sys.path = old_sys_path

import os
import site
Expand Down

0 comments on commit 0dafc47

Please sign in to comment.