compat.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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. Various classes and functions to provide some backwards-compatibility with previous versions of Python onward.
  13. """
  14. from __future__ import annotations
  15. import errno
  16. import importlib.machinery
  17. import importlib.util
  18. import os
  19. import platform
  20. import site
  21. import subprocess
  22. import sys
  23. import sysconfig
  24. import shutil
  25. import types
  26. from PyInstaller._shared_with_waf import _pyi_machine
  27. from PyInstaller.exceptions import ExecCommandFailed
  28. # hatch_build.py sets this environment variable to avoid errors due to unmet run-time dependencies. The
  29. # PyInstaller.compat module is imported by hatch_build.py to build wheels, and some dependencies that are otherwise
  30. # required at run-time (importlib-metadata on python < 3.10, pywin32-ctypes on Windows) might not be present while
  31. # building wheels, nor are they required during that phase.
  32. _setup_py_mode = os.environ.get('_PYINSTALLER_SETUP', '0') != '0'
  33. # PyInstaller requires importlib.metadata from python >= 3.10 stdlib, or equivalent importlib-metadata >= 4.6.
  34. if _setup_py_mode:
  35. importlib_metadata = None
  36. else:
  37. if sys.version_info >= (3, 10):
  38. import importlib.metadata as importlib_metadata
  39. else:
  40. try:
  41. import importlib_metadata
  42. except ImportError as e:
  43. from PyInstaller.exceptions import ImportlibMetadataError
  44. raise ImportlibMetadataError() from e
  45. import packaging.version # For importlib_metadata version check
  46. # Validate the version
  47. if packaging.version.parse(importlib_metadata.version("importlib-metadata")) < packaging.version.parse("4.6"):
  48. from PyInstaller.exceptions import ImportlibMetadataError
  49. raise ImportlibMetadataError()
  50. # Strict collect mode, which raises error when trying to collect duplicate files into PKG/CArchive or COLLECT.
  51. strict_collect_mode = os.environ.get("PYINSTALLER_STRICT_COLLECT_MODE", "0") != "0"
  52. # Copied from https://docs.python.org/3/library/platform.html#cross-platform.
  53. is_64bits: bool = sys.maxsize > 2**32
  54. # Distinguish specific code for various Python versions. Variables 'is_pyXY' mean that Python X.Y and up is supported.
  55. # Keep even unsupported versions here to keep 3rd-party hooks working.
  56. is_py35 = sys.version_info >= (3, 5)
  57. is_py36 = sys.version_info >= (3, 6)
  58. is_py37 = sys.version_info >= (3, 7)
  59. is_py38 = sys.version_info >= (3, 8)
  60. is_py39 = sys.version_info >= (3, 9)
  61. is_py310 = sys.version_info >= (3, 10)
  62. is_py311 = sys.version_info >= (3, 11)
  63. is_py312 = sys.version_info >= (3, 12)
  64. is_py313 = sys.version_info >= (3, 13)
  65. is_py314 = sys.version_info >= (3, 14)
  66. is_py315 = sys.version_info >= (3, 15)
  67. is_win = sys.platform.startswith('win')
  68. is_win_10 = is_win and (platform.win32_ver()[0] == '10')
  69. is_win_11 = is_win and (platform.win32_ver()[0] == '11')
  70. is_win_wine = False # Running under Wine; determined later on.
  71. is_cygwin = sys.platform == 'cygwin'
  72. is_darwin = sys.platform == 'darwin' # macOS
  73. # Unix platforms
  74. is_android = sys.platform.startswith('android')
  75. is_linux = sys.platform.startswith('linux') or is_android # For our intents and purposes, Android is also Linux.
  76. is_solar = sys.platform.startswith('sun') # Solaris
  77. is_aix = sys.platform.startswith('aix')
  78. is_freebsd = sys.platform.startswith('freebsd')
  79. is_openbsd = sys.platform.startswith('openbsd')
  80. is_hpux = sys.platform.startswith('hp-ux')
  81. # Some code parts are similar to several unix platforms (e.g. Linux, Solaris, AIX).
  82. # macOS is not considered as unix since there are many platform-specific details for Mac in PyInstaller.
  83. is_unix = is_linux or is_solar or is_aix or is_freebsd or is_hpux or is_openbsd
  84. # Linux distributions such as Alpine or OpenWRT use musl as their libc implementation and resultantly need specially
  85. # compiled bootloaders. On musl systems, ldd with no arguments prints 'musl' and its version.
  86. is_musl = is_linux and "musl" in subprocess.run(["ldd"], capture_output=True, encoding="utf-8").stderr
  87. # Termux - terminal emulator and Linux environment app for Android.
  88. # With python >= 3.13, this could also be directly inferred from `sys.platform` or `platform.system()` (see PEP-738),
  89. # and `is_android` will also be set to True; this is not the case with earlier python versions (that people might still
  90. # have installed in their Termux environments), so for now, we keep the legacy check.
  91. is_termux = is_linux and hasattr(sys, 'getandroidapilevel')
  92. # macOS version
  93. _macos_ver = tuple(int(x) for x in platform.mac_ver()[0].split('.')) if is_darwin else None
  94. # macOS 11 (Big Sur): if python is not compiled with Big Sur support, it ends up in compatibility mode by default, which
  95. # is indicated by platform.mac_ver() returning '10.16'. The lack of proper Big Sur support breaks find_library()
  96. # function from ctypes.util module, as starting with Big Sur, shared libraries are not visible on disk anymore. Support
  97. # for the new library search mechanism was added in python 3.9 when compiled with Big Sur support. In such cases,
  98. # platform.mac_ver() reports version as '11.x'. The behavior can be further modified via SYSTEM_VERSION_COMPAT
  99. # environment variable; which allows explicitly enabling or disabling the compatibility mode. However, note that
  100. # disabling the compatibility mode and using python that does not properly support Big Sur still leaves find_library()
  101. # broken (which is a scenario that we ignore at the moment).
  102. # The same logic applies to macOS 12 (Monterey).
  103. is_macos_11_compat = bool(_macos_ver) and _macos_ver[0:2] == (10, 16) # Big Sur or newer in compat mode
  104. is_macos_11_native = bool(_macos_ver) and _macos_ver[0:2] >= (11, 0) # Big Sur or newer in native mode
  105. is_macos_11 = is_macos_11_compat or is_macos_11_native # Big Sur or newer
  106. # Check if python >= 3.13 was built with Py_GIL_DISABLED / free-threading (PEP703).
  107. #
  108. # This affects the shared library name, which has the "t" ABI suffix, as per:
  109. # https://github.com/python/steering-council/issues/221#issuecomment-1841593283
  110. #
  111. # It also affects the layout of PyConfig structure used by bootloader; consequently we need to inform bootloader what
  112. # kind of build it is dealing with (only in python 3.13; with 3.14 and later, we use PEP741 configuration API in the
  113. # bootloader, and do not need to know the layout of PyConfig structure anymore)
  114. is_nogil = bool(sysconfig.get_config_var('Py_GIL_DISABLED'))
  115. # In a virtual environment created by virtualenv (github.com/pypa/virtualenv) there exists sys.real_prefix with the path
  116. # to the base Python installation from which the virtual environment was created. This is true regardless of the version
  117. # of Python used to execute the virtualenv command.
  118. #
  119. # In a virtual environment created by the venv module available in the Python standard lib, there exists sys.base_prefix
  120. # with the path to the base implementation. This does not exist in a virtual environment created by virtualenv.
  121. #
  122. # The following code creates compat.is_venv and is.virtualenv that are True when running a virtual environment, and also
  123. # compat.base_prefix with the path to the base Python installation.
  124. base_prefix: str = os.path.abspath(getattr(sys, 'real_prefix', getattr(sys, 'base_prefix', sys.prefix)))
  125. # Ensure `base_prefix` is not containing any relative parts.
  126. is_venv = is_virtualenv = base_prefix != os.path.abspath(sys.prefix)
  127. # Conda environments sometimes have different paths or apply patches to packages that can affect how a hook or package
  128. # should access resources. Method for determining conda taken from https://stackoverflow.com/questions/47610844#47610844
  129. is_conda = os.path.isdir(os.path.join(base_prefix, 'conda-meta'))
  130. # Similar to ``is_conda`` but is ``False`` using another ``venv``-like manager on top. In this case, no packages
  131. # encountered will be conda packages meaning that the default non-conda behaviour is generally desired from PyInstaller.
  132. is_pure_conda = os.path.isdir(os.path.join(sys.prefix, 'conda-meta'))
  133. # Full path to python interpreter.
  134. python_executable = getattr(sys, '_base_executable', sys.executable)
  135. # Is this Python from Microsoft App Store (Windows only)? Python from Microsoft App Store has executable pointing at
  136. # empty shims.
  137. is_ms_app_store = is_win and os.path.getsize(python_executable) == 0
  138. if is_ms_app_store:
  139. # Locate the actual executable inside base_prefix.
  140. python_executable = os.path.join(base_prefix, os.path.basename(python_executable))
  141. if not os.path.exists(python_executable):
  142. raise SystemExit(
  143. 'ERROR: PyInstaller cannot locate real python executable belonging to Python from Microsoft App Store!'
  144. )
  145. # Bytecode magic value
  146. BYTECODE_MAGIC = importlib.util.MAGIC_NUMBER
  147. # List of suffixes for Python C extension modules.
  148. EXTENSION_SUFFIXES = importlib.machinery.EXTENSION_SUFFIXES
  149. ALL_SUFFIXES = importlib.machinery.all_suffixes()
  150. # On Windows we require pywin32-ctypes.
  151. # -> all pyinstaller modules should use win32api from PyInstaller.compat to
  152. # ensure that it can work on MSYS2 (which requires pywin32-ctypes)
  153. if is_win:
  154. if _setup_py_mode:
  155. pywintypes = None
  156. win32api = None
  157. else:
  158. try:
  159. # Hide the `cffi` package from win32-ctypes by temporarily blocking its import. This ensures that `ctypes`
  160. # backend is always used, even if `cffi` is available. The `cffi` backend uses `pycparser`, which is
  161. # incompatible with -OO mode (2nd optimization level) due to its removal of docstrings.
  162. # See https://github.com/pyinstaller/pyinstaller/issues/6345
  163. # On the off chance that `cffi` has already been imported, store the `sys.modules` entry so we can restore
  164. # it after importing `pywin32-ctypes` modules.
  165. orig_cffi = sys.modules.get('cffi')
  166. sys.modules['cffi'] = None
  167. from win32ctypes.pywin32 import pywintypes # noqa: F401, E402
  168. from win32ctypes.pywin32 import win32api # noqa: F401, E402
  169. except ImportError as e:
  170. raise SystemExit(
  171. 'ERROR: Could not import `pywintypes` or `win32api` from `win32ctypes.pywin32`.\n'
  172. 'Please make sure that `pywin32-ctypes` is installed and importable, for example:\n\n'
  173. 'pip install pywin32-ctypes\n'
  174. ) from e
  175. finally:
  176. # Unblock `cffi`.
  177. if orig_cffi is not None:
  178. sys.modules['cffi'] = orig_cffi
  179. else:
  180. del sys.modules['cffi']
  181. del orig_cffi
  182. # macOS's platform.architecture() can be buggy, so we do this manually here. Based off the python documentation:
  183. # https://docs.python.org/3/library/platform.html#platform.architecture
  184. if is_darwin:
  185. architecture = '64bit' if sys.maxsize > 2**32 else '32bit'
  186. else:
  187. architecture = platform.architecture()[0]
  188. # Cygwin needs special handling, because platform.system() contains identifiers such as MSYS_NT-10.0-19042 and
  189. # CYGWIN_NT-10.0-19042 that do not fit PyInstaller's OS naming scheme. Explicitly set `system` to 'Cygwin'.
  190. system = 'Cygwin' if is_cygwin else platform.system()
  191. # Similarly, fold Android (reported by python >= 3.13 in Termux environment) back into Linux.
  192. if system == 'Android':
  193. system = 'Linux'
  194. # Machine suffix for bootloader.
  195. if is_win:
  196. # On Windows ARM64 using an x64 Python environment, platform.machine() returns ARM64 but
  197. # we really want the bootloader that matches the Python environment instead of the OS.
  198. machine = _pyi_machine(os.environ.get("PROCESSOR_ARCHITECTURE", platform.machine()), platform.system())
  199. else:
  200. machine = _pyi_machine(platform.machine(), platform.system())
  201. # Wine detection and support
  202. def is_wine_dll(filename: str | os.PathLike):
  203. """
  204. Check if the given PE file is a Wine DLL (PE-converted built-in, or fake/placeholder one).
  205. Returns True if the given file is a Wine DLL, False if not (or if file cannot be analyzed or does not exist).
  206. """
  207. _WINE_SIGNATURES = (
  208. b'Wine builtin DLL', # PE-converted Wine DLL
  209. b'Wine placeholder DLL', # Fake/placeholder Wine DLL
  210. )
  211. _MAX_LEN = max([len(sig) for sig in _WINE_SIGNATURES])
  212. # Wine places their DLL signature in the padding area between the IMAGE_DOS_HEADER and IMAGE_NT_HEADERS. So we need
  213. # to compare the bytes that come right after IMAGE_DOS_HEADER, i.e., after initial 64 bytes. We can read the file
  214. # directly and avoid using the pefile library to avoid performance penalty associated with full header parsing.
  215. try:
  216. with open(filename, 'rb') as fp:
  217. fp.seek(64)
  218. signature = fp.read(_MAX_LEN)
  219. return signature.startswith(_WINE_SIGNATURES)
  220. except Exception:
  221. pass
  222. return False
  223. if is_win:
  224. try:
  225. import ctypes.util # noqa: E402
  226. is_win_wine = is_wine_dll(ctypes.util.find_library('kernel32'))
  227. except Exception:
  228. pass
  229. # Set and get environment variables does not handle unicode strings correctly on Windows.
  230. # Acting on os.environ instead of using getenv()/setenv()/unsetenv(), as suggested in
  231. # <http://docs.python.org/library/os.html#os.environ>: "Calling putenv() directly does not change os.environ, so it is
  232. # better to modify os.environ." (Same for unsetenv.)
  233. def getenv(name: str, default: str | None = None):
  234. """
  235. Returns unicode string containing value of environment variable 'name'.
  236. """
  237. return os.environ.get(name, default)
  238. def setenv(name: str, value: str):
  239. """
  240. Accepts unicode string and set it as environment variable 'name' containing value 'value'.
  241. """
  242. os.environ[name] = value
  243. def unsetenv(name: str):
  244. """
  245. Delete the environment variable 'name'.
  246. """
  247. # Some platforms (e.g., AIX) do not support `os.unsetenv()` and thus `del os.environ[name]` has no effect on the
  248. # real environment. For this case, we set the value to the empty string.
  249. os.environ[name] = ""
  250. del os.environ[name]
  251. # Exec commands in subprocesses.
  252. def exec_command(
  253. *cmdargs: str, encoding: str | None = None, raise_enoent: bool | None = None, **kwargs: int | bool | list | None
  254. ):
  255. """
  256. Run the command specified by the passed positional arguments, optionally configured by the passed keyword arguments.
  257. .. DANGER::
  258. **Ignore this function's return value** -- unless this command's standard output contains _only_ pathnames, in
  259. which case this function returns the correct filesystem-encoded string expected by PyInstaller. In all other
  260. cases, this function's return value is _not_ safely usable.
  261. For backward compatibility, this function's return value non-portably depends on the current Python version and
  262. passed keyword arguments:
  263. * Under Python 3.x, this value is a **decoded `str` string**. However, even this value is _not_ necessarily
  264. safely usable:
  265. * If the `encoding` parameter is passed, this value is guaranteed to be safely usable.
  266. * Else, this value _cannot_ be safely used for any purpose (e.g., string manipulation or parsing), except to be
  267. passed directly to another non-Python command. Why? Because this value has been decoded with the encoding
  268. specified by `sys.getfilesystemencoding()`, the encoding used by `os.fsencode()` and `os.fsdecode()` to
  269. convert from platform-agnostic to platform-specific pathnames. This is _not_ necessarily the encoding with
  270. which this command's standard output was encoded. Cue edge-case decoding exceptions.
  271. Parameters
  272. ----------
  273. cmdargs :
  274. Variadic list whose:
  275. 1. Mandatory first element is the absolute path, relative path, or basename in the current `${PATH}` of the
  276. command to run.
  277. 2. Optional remaining elements are arguments to pass to this command.
  278. encoding : str, optional
  279. Optional keyword argument specifying the encoding with which to decode this command's standard output under
  280. Python 3. As this function's return value should be ignored, this argument should _never_ be passed.
  281. raise_enoent : boolean, optional
  282. Optional keyword argument to simply raise the exception if the executing the command fails since to the command
  283. is not found. This is useful to checking id a command exists.
  284. All remaining keyword arguments are passed as is to the `subprocess.Popen()` constructor.
  285. Returns
  286. ----------
  287. str
  288. Ignore this value. See discussion above.
  289. """
  290. proc = subprocess.Popen(cmdargs, stdout=subprocess.PIPE, **kwargs)
  291. try:
  292. out = proc.communicate(timeout=60)[0]
  293. except OSError as e:
  294. if raise_enoent and e.errno == errno.ENOENT:
  295. raise
  296. print('--' * 20, file=sys.stderr)
  297. print("Error running '%s':" % " ".join(cmdargs), file=sys.stderr)
  298. print(e, file=sys.stderr)
  299. print('--' * 20, file=sys.stderr)
  300. raise ExecCommandFailed("ERROR: Executing command failed!") from e
  301. except subprocess.TimeoutExpired:
  302. proc.kill()
  303. raise
  304. # stdout/stderr are returned as a byte array NOT as string, so we need to convert that to proper encoding.
  305. try:
  306. if encoding:
  307. out = out.decode(encoding)
  308. else:
  309. # If no encoding is given, assume we are reading filenames from stdout only because it is the common case.
  310. out = os.fsdecode(out)
  311. except UnicodeDecodeError as e:
  312. # The sub-process used a different encoding; provide more information to ease debugging.
  313. print('--' * 20, file=sys.stderr)
  314. print(str(e), file=sys.stderr)
  315. print('These are the bytes around the offending byte:', file=sys.stderr)
  316. print('--' * 20, file=sys.stderr)
  317. raise
  318. return out
  319. def exec_command_rc(*cmdargs: str, **kwargs: float | bool | list | None):
  320. """
  321. Return the exit code of the command specified by the passed positional arguments, optionally configured by the
  322. passed keyword arguments.
  323. Parameters
  324. ----------
  325. cmdargs : list
  326. Variadic list whose:
  327. 1. Mandatory first element is the absolute path, relative path, or basename in the current `${PATH}` of the
  328. command to run.
  329. 2. Optional remaining elements are arguments to pass to this command.
  330. All keyword arguments are passed as is to the `subprocess.call()` function.
  331. Returns
  332. ----------
  333. int
  334. This command's exit code as an unsigned byte in the range `[0, 255]`, where 0 signifies success and all other
  335. values signal a failure.
  336. """
  337. # 'encoding' keyword is not supported for 'subprocess.call'; remove it from kwargs.
  338. if 'encoding' in kwargs:
  339. kwargs.pop('encoding')
  340. return subprocess.call(cmdargs, **kwargs)
  341. def exec_command_all(*cmdargs: str, encoding: str | None = None, **kwargs: int | bool | list | None):
  342. """
  343. Run the command specified by the passed positional arguments, optionally configured by the passed keyword arguments.
  344. .. DANGER::
  345. **Ignore this function's return value.** If this command's standard output consists solely of pathnames, consider
  346. calling `exec_command()`
  347. Parameters
  348. ----------
  349. cmdargs : str
  350. Variadic list whose:
  351. 1. Mandatory first element is the absolute path, relative path, or basename in the current `${PATH}` of the
  352. command to run.
  353. 2. Optional remaining elements are arguments to pass to this command.
  354. encoding : str, optional
  355. Optional keyword argument specifying the encoding with which to decode this command's standard output. As this
  356. function's return value should be ignored, this argument should _never_ be passed.
  357. All remaining keyword arguments are passed as is to the `subprocess.Popen()` constructor.
  358. Returns
  359. ----------
  360. (int, str, str)
  361. Ignore this 3-element tuple `(exit_code, stdout, stderr)`. See the `exec_command()` function for discussion.
  362. """
  363. proc = subprocess.Popen(
  364. cmdargs,
  365. bufsize=-1, # Default OS buffer size.
  366. stdout=subprocess.PIPE,
  367. stderr=subprocess.PIPE,
  368. **kwargs
  369. )
  370. # Waits for subprocess to complete.
  371. try:
  372. out, err = proc.communicate(timeout=60)
  373. except subprocess.TimeoutExpired:
  374. proc.kill()
  375. raise
  376. # stdout/stderr are returned as a byte array NOT as string. Thus we need to convert that to proper encoding.
  377. try:
  378. if encoding:
  379. out = out.decode(encoding)
  380. err = err.decode(encoding)
  381. else:
  382. # If no encoding is given, assume we're reading filenames from stdout only because it's the common case.
  383. out = os.fsdecode(out)
  384. err = os.fsdecode(err)
  385. except UnicodeDecodeError as e:
  386. # The sub-process used a different encoding, provide more information to ease debugging.
  387. print('--' * 20, file=sys.stderr)
  388. print(str(e), file=sys.stderr)
  389. print('These are the bytes around the offending byte:', file=sys.stderr)
  390. print('--' * 20, file=sys.stderr)
  391. raise
  392. return proc.returncode, out, err
  393. def __wrap_python(args, kwargs):
  394. cmdargs = [sys.executable]
  395. # macOS supports universal binaries (binary for multiple architectures. We need to ensure that subprocess
  396. # binaries are running for the same architecture as python executable. It is necessary to run binaries with 'arch'
  397. # command.
  398. if is_darwin:
  399. if architecture == '64bit':
  400. if platform.machine() == 'arm64':
  401. py_prefix = ['arch', '-arm64'] # Apple M1
  402. else:
  403. py_prefix = ['arch', '-x86_64'] # Intel
  404. elif architecture == '32bit':
  405. py_prefix = ['arch', '-i386']
  406. else:
  407. py_prefix = []
  408. # Since macOS 10.11, the environment variable DYLD_LIBRARY_PATH is no more inherited by child processes, so we
  409. # proactively propagate the current value using the `-e` option of the `arch` command.
  410. if 'DYLD_LIBRARY_PATH' in os.environ:
  411. path = os.environ['DYLD_LIBRARY_PATH']
  412. py_prefix += ['-e', 'DYLD_LIBRARY_PATH=%s' % path]
  413. cmdargs = py_prefix + cmdargs
  414. if not __debug__:
  415. cmdargs.append('-O')
  416. cmdargs.extend(args)
  417. env = kwargs.get('env')
  418. if env is None:
  419. env = dict(**os.environ)
  420. # Ensure python 3 subprocess writes 'str' as utf-8
  421. env['PYTHONIOENCODING'] = 'UTF-8'
  422. # ... and ensure we read output as utf-8
  423. kwargs['encoding'] = 'UTF-8'
  424. return cmdargs, kwargs
  425. def exec_python(*args: str, **kwargs: str | None):
  426. """
  427. Wrap running python script in a subprocess.
  428. Return stdout of the invoked command.
  429. """
  430. cmdargs, kwargs = __wrap_python(args, kwargs)
  431. return exec_command(*cmdargs, **kwargs)
  432. def exec_python_rc(*args: str, **kwargs: str | None):
  433. """
  434. Wrap running python script in a subprocess.
  435. Return exit code of the invoked command.
  436. """
  437. cmdargs, kwargs = __wrap_python(args, kwargs)
  438. return exec_command_rc(*cmdargs, **kwargs)
  439. # Path handling.
  440. # Site-packages functions - use native function if available.
  441. def getsitepackages(prefixes: list | None = None):
  442. """
  443. Returns a list containing all global site-packages directories.
  444. For each directory present in ``prefixes`` (or the global ``PREFIXES``), this function finds its `site-packages`
  445. subdirectory depending on the system environment, and returns a list of full paths.
  446. """
  447. # This implementation was copied from the ``site`` module, python 3.7.3.
  448. sitepackages = []
  449. seen = set()
  450. if prefixes is None:
  451. prefixes = [sys.prefix, sys.exec_prefix]
  452. for prefix in prefixes:
  453. if not prefix or prefix in seen:
  454. continue
  455. seen.add(prefix)
  456. if os.sep == '/':
  457. sitepackages.append(os.path.join(prefix, "lib", "python%d.%d" % sys.version_info[:2], "site-packages"))
  458. else:
  459. sitepackages.append(prefix)
  460. sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
  461. return sitepackages
  462. # Backported for virtualenv. Module 'site' in virtualenv might not have this attribute.
  463. getsitepackages = getattr(site, 'getsitepackages', getsitepackages)
  464. # Wrapper to load a module from a Python source file. This function loads import hooks when processing them.
  465. def importlib_load_source(name: str, pathname: str):
  466. # Import module from a file.
  467. mod_loader = importlib.machinery.SourceFileLoader(name, pathname)
  468. mod = types.ModuleType(mod_loader.name)
  469. mod.__file__ = mod_loader.get_filename() # Some hooks require __file__ attribute in their namespace
  470. mod_loader.exec_module(mod)
  471. return mod
  472. # Patterns of module names that should be bundled into the base_library.zip to be available during bootstrap.
  473. # These modules include direct or indirect dependencies of encodings.* modules. The encodings modules must be
  474. # recursively included to set the I/O encoding during python startup. Similarly, this list should include
  475. # modules used by PyInstaller's bootstrap scripts and modules (loader/pyi*.py)
  476. PY3_BASE_MODULES = {
  477. '_collections_abc',
  478. '_weakrefset',
  479. 'abc',
  480. 'codecs',
  481. 'collections',
  482. 'copyreg',
  483. 'encodings',
  484. 'enum',
  485. 'functools',
  486. 'genericpath', # dependency of os.path
  487. 'io',
  488. 'heapq',
  489. 'keyword',
  490. 'linecache',
  491. 'locale',
  492. 'ntpath', # dependency of os.path
  493. 'operator',
  494. 'os',
  495. 'posixpath', # dependency of os.path
  496. 're',
  497. 'reprlib',
  498. 'stat', # dependency of os.path
  499. 'traceback', # for startup errors
  500. 'types',
  501. 'weakref',
  502. 'warnings',
  503. }
  504. if not is_py310:
  505. PY3_BASE_MODULES.add('_bootlocale')
  506. if is_android and is_py313:
  507. PY3_BASE_MODULES.add('_android_support')
  508. PY3_BASE_MODULES.add('threading') # dependency of _android_support
  509. if not is_py315:
  510. PY3_BASE_MODULES.add('sre_compile')
  511. PY3_BASE_MODULES.add('sre_constants')
  512. PY3_BASE_MODULES.add('sre_parse')
  513. # Object types of Pure Python modules in modulegraph dependency graph.
  514. # Pure Python modules have code object (attribute co_code).
  515. PURE_PYTHON_MODULE_TYPES = {
  516. 'SourceModule',
  517. 'CompiledModule',
  518. 'Package',
  519. 'NamespacePackage',
  520. # Deprecated.
  521. # TODO Could these module types be removed?
  522. 'FlatPackage',
  523. 'ArchiveModule',
  524. }
  525. # Object types of special Python modules (built-in, run-time, namespace package) in modulegraph dependency graph that do
  526. # not have code object.
  527. SPECIAL_MODULE_TYPES = {
  528. # Omit AliasNode from here (and consequently from VALID_MODULE_TYPES), in order to prevent PyiModuleGraph from
  529. # running standard hooks for aliased modules.
  530. #'AliasNode',
  531. 'BuiltinModule',
  532. 'RuntimeModule',
  533. 'RuntimePackage',
  534. # PyInstaller handles scripts differently and not as standard Python modules.
  535. 'Script',
  536. }
  537. # Object types of Binary Python modules (extensions, etc) in modulegraph dependency graph.
  538. BINARY_MODULE_TYPES = {
  539. 'Extension',
  540. 'ExtensionPackage',
  541. }
  542. # Object types of valid Python modules in modulegraph dependency graph.
  543. VALID_MODULE_TYPES = PURE_PYTHON_MODULE_TYPES | SPECIAL_MODULE_TYPES | BINARY_MODULE_TYPES
  544. # Object types of bad/missing/invalid Python modules in modulegraph dependency graph.
  545. # TODO: should be 'Invalid' module types also in the 'MISSING' set?
  546. BAD_MODULE_TYPES = {
  547. 'BadModule',
  548. 'ExcludedModule',
  549. 'InvalidSourceModule',
  550. 'InvalidCompiledModule',
  551. 'MissingModule',
  552. # Runtime modules and packages are technically valid rather than bad, but exist only in-memory rather than on-disk
  553. # (typically due to pre_safe_import_module() hooks), and hence cannot be physically frozen. For simplicity, these
  554. # nodes are categorized as bad rather than valid.
  555. 'RuntimeModule',
  556. 'RuntimePackage',
  557. }
  558. ALL_MODULE_TYPES = VALID_MODULE_TYPES | BAD_MODULE_TYPES
  559. # TODO: review this mapping to TOC, remove useless entries.
  560. # Dictionary to map ModuleGraph node types to TOC typecodes.
  561. MODULE_TYPES_TO_TOC_DICT = {
  562. # Pure modules.
  563. 'AliasNode': 'PYMODULE',
  564. 'Script': 'PYSOURCE',
  565. 'SourceModule': 'PYMODULE',
  566. 'CompiledModule': 'PYMODULE',
  567. 'Package': 'PYMODULE',
  568. 'FlatPackage': 'PYMODULE',
  569. 'ArchiveModule': 'PYMODULE',
  570. # Binary modules.
  571. 'Extension': 'EXTENSION',
  572. 'ExtensionPackage': 'EXTENSION',
  573. # Special valid modules.
  574. 'BuiltinModule': 'BUILTIN',
  575. 'NamespacePackage': 'PYMODULE',
  576. # Bad modules.
  577. 'BadModule': 'bad',
  578. 'ExcludedModule': 'excluded',
  579. 'InvalidSourceModule': 'invalid',
  580. 'InvalidCompiledModule': 'invalid',
  581. 'MissingModule': 'missing',
  582. 'RuntimeModule': 'runtime',
  583. 'RuntimePackage': 'runtime',
  584. # Other.
  585. 'does not occur': 'BINARY',
  586. }
  587. def check_requirements():
  588. """
  589. Verify that all requirements to run PyInstaller are met.
  590. Fail hard if any requirement is not met.
  591. """
  592. # Fail hard if Python does not have minimum required version
  593. if sys.version_info < (3, 8):
  594. raise EnvironmentError('PyInstaller requires Python 3.8 or newer.')
  595. if sys.implementation.name != "cpython":
  596. raise SystemExit(f"ERROR: PyInstaller does not support {sys.implementation.name}. Only CPython is supported.")
  597. if getattr(sys, "frozen", False):
  598. raise SystemExit("ERROR: PyInstaller can not be ran on itself")
  599. # There are some old packages which used to be backports of libraries which are now part of the standard library.
  600. # These backports are now unmaintained and contain only an older subset of features leading to obscure errors like
  601. # "enum has not attribute IntFlag" if installed.
  602. from importlib.metadata import distribution, PackageNotFoundError
  603. for name in ["enum34", "typing", "pathlib"]:
  604. try:
  605. dist = distribution(name)
  606. except PackageNotFoundError:
  607. continue
  608. remove = "conda remove" if is_conda else f'"{sys.executable}" -m pip uninstall {name}'
  609. raise SystemExit(
  610. f"ERROR: The '{name}' package is an obsolete backport of a standard library package and is incompatible "
  611. f"with PyInstaller. Please remove this package (located in {dist.locate_file('')}) using\n {remove}\n"
  612. "then try again."
  613. )
  614. # Bail out if binutils is not installed.
  615. if is_linux and shutil.which("objdump") is None:
  616. raise SystemExit(
  617. "ERROR: On Linux, objdump is required. It is typically provided by the 'binutils' package "
  618. "installable via your Linux distribution's package manager."
  619. )