hook-distutils.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # -----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2023, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. # -----------------------------------------------------------------------------
  11. """
  12. `distutils`-specific pre-find module path hook.
  13. When run from within a virtual environment, this hook changes the `__path__` of the `distutils` package to
  14. that of the system-wide rather than virtual-environment-specific `distutils` package. While the former is suitable for
  15. freezing, the latter is intended for use _only_ from within virtual environments.
  16. NOTE: this behavior seems to be specific to virtual environments created by (an old?) version of `virtualenv`; it is not
  17. applicable to virtual environments created by the `venv`.
  18. """
  19. import pathlib
  20. from PyInstaller.utils.hooks import logger, get_module_file_attribute
  21. def pre_find_module_path(api):
  22. # Absolute path of the system-wide "distutils" package when run from within a venv or None otherwise.
  23. # opcode is not a virtualenv module, so we can use it to find the stdlib. Technique taken from virtualenv's
  24. # "distutils" package detection at
  25. # https://github.com/pypa/virtualenv/blob/16.3.0/virtualenv_embedded/distutils-init.py#L5
  26. # As opcode is a module, stdlib path corresponds to the parent directory of its ``__file__`` attribute.
  27. stdlib_path = pathlib.Path(get_module_file_attribute('opcode')).parent.resolve()
  28. # As distutils is a package, we need to consider the grandparent directory of its ``__file__`` attribute.
  29. distutils_path = pathlib.Path(get_module_file_attribute('distutils')).parent.parent.resolve()
  30. if distutils_path.name == 'setuptools':
  31. logger.debug("distutils: provided by setuptools")
  32. elif distutils_path == stdlib_path:
  33. logger.debug("distutils: provided by stdlib")
  34. else:
  35. # Find this package in stdlib.
  36. stdlib_path = str(stdlib_path)
  37. logger.debug("distutils: virtualenv shim - retargeting to stdlib dir %r", stdlib_path)
  38. api.search_dirs = [stdlib_path]