build_main.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2022, 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. Build packages using spec files.
  13. NOTE: All global variables, classes and imported modules create API for .spec files.
  14. """
  15. import glob
  16. import os
  17. import pprint
  18. import shutil
  19. import sys
  20. from PyInstaller import DEFAULT_DISTPATH, DEFAULT_WORKPATH, HOMEPATH, compat
  21. from PyInstaller import log as logging
  22. from PyInstaller.archive import pyz_crypto
  23. from PyInstaller.building.api import COLLECT, EXE, MERGE, PYZ
  24. from PyInstaller.building.datastruct import TOC, Target, Tree, _check_guts_eq
  25. from PyInstaller.building.osx import BUNDLE
  26. from PyInstaller.building.splash import Splash
  27. from PyInstaller.building.toc_conversion import DependencyProcessor
  28. from PyInstaller.building.utils import (_check_guts_toc_mtime, _should_include_system_binary, format_binaries_and_datas)
  29. from PyInstaller.compat import PYDYLIB_NAMES, is_win
  30. from PyInstaller.depend import bindepend
  31. from PyInstaller.depend.analysis import initialize_modgraph
  32. from PyInstaller.depend.utils import (create_py3_base_library, scan_code_for_ctypes)
  33. from PyInstaller import isolated
  34. from PyInstaller.utils.misc import (
  35. absnormpath, compile_py_files, get_path_to_toplevel_modules, get_unicode_modules, mtime
  36. )
  37. if is_win:
  38. from PyInstaller.utils.win32 import winmanifest
  39. logger = logging.getLogger(__name__)
  40. STRINGTYPE = type('')
  41. TUPLETYPE = type((None,))
  42. rthooks = {}
  43. # Place where the loader modules and initialization scripts live.
  44. _init_code_path = os.path.join(HOMEPATH, 'PyInstaller', 'loader')
  45. IMPORT_TYPES = [
  46. 'top-level', 'conditional', 'delayed', 'delayed, conditional', 'optional', 'conditional, optional',
  47. 'delayed, optional', 'delayed, conditional, optional'
  48. ]
  49. WARNFILE_HEADER = """\
  50. This file lists modules PyInstaller was not able to find. This does not
  51. necessarily mean this module is required for running your program. Python and
  52. Python 3rd-party packages include a lot of conditional or optional modules. For
  53. example the module 'ntpath' only exists on Windows, whereas the module
  54. 'posixpath' only exists on Posix systems.
  55. Types if import:
  56. * top-level: imported at the top-level - look at these first
  57. * conditional: imported within an if-statement
  58. * delayed: imported within a function
  59. * optional: imported within a try-except-statement
  60. IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
  61. tracking down the missing module yourself. Thanks!
  62. """
  63. # TODO find better place for function.
  64. def setupUPXFlags():
  65. f = compat.getenv("UPX", "")
  66. if is_win:
  67. # Binaries built with Visual Studio 7.1 require --strip-loadconf or they will not compress. Configure.py makes
  68. # sure that UPX is new enough to support --strip-loadconf.
  69. f = "--strip-loadconf " + f
  70. # Do not compress any icon, so that additional icons in the executable can still be externally bound.
  71. f = "--compress-icons=0 " + f
  72. f = "--best " + f
  73. compat.setenv("UPX", f)
  74. @isolated.decorate
  75. def discover_hook_directories():
  76. """
  77. Discover hook directories via pkg_resources and pyinstaller40 entry points. Perform the discovery in a subprocess
  78. to avoid importing the package(s) in the main process.
  79. :return: list of discovered hook directories.
  80. """
  81. import sys # noqa: F401
  82. from traceback import format_exception_only
  83. import pkg_resources
  84. from PyInstaller.log import logger
  85. entry_points = pkg_resources.iter_entry_points('pyinstaller40', 'hook-dirs')
  86. hook_directories = []
  87. for entry_point in entry_points:
  88. try:
  89. hook_directories.extend(entry_point.load()())
  90. except Exception as e:
  91. msg = "".join(format_exception_only(type(e), e)).strip()
  92. logger.warning("discover_hook_directories: Failed to process hook entry point '%s': %s", entry_point, msg)
  93. logger.debug("discover_hook_directories: Hook directories: %s", hook_directories)
  94. return hook_directories
  95. # NOTE: this helper is called via isolated.call() in Analysis.assemble(). We cannot use @isolated.decorate here, because
  96. # one of the tests (test_regression::test_issue_5131) needs to be able to monkey-patch it, in order to override the
  97. # bindepend.getImports() in the isolated subprocess (!) with its own implementation...
  98. def find_binary_dependencies(binaries, binding_redirects, import_packages):
  99. """
  100. Find dynamic dependencies (linked shared libraries) for the provided list of binaries.
  101. Before scanning the binaries, the function imports the packages from provided list of packages to import, to ensure
  102. that library search paths are properly set up (i.e., if a package sets up search paths when imported). Therefore,
  103. this function *must* always be called in an isolated subprocess to avoid import leaks!
  104. binaries
  105. List of binaries to scan for dynamic dependencies.
  106. binding_redirects
  107. List of assembly binding redirects.
  108. import_packages
  109. List of packages to import prior to scanning binaries.
  110. :return: expanded list of binaries and then dependencies.
  111. """
  112. from PyInstaller.depend import bindepend
  113. from PyInstaller import compat
  114. # In the case of MS App Store python, add compat.base_prefix to extra library search paths. In addition to
  115. # python38.dll (that we manage to resolve by other means, if necessary), this directory also contains
  116. # python3.dll that might be required by some 3rd-party extension modules, and would otherwise end up missing
  117. # during the dependency analysis.
  118. extra_libdirs = []
  119. if compat.is_ms_app_store:
  120. extra_libdirs.append(compat.base_prefix)
  121. # Import collected packages to set up environment
  122. for package in import_packages:
  123. try:
  124. __import__(package)
  125. except Exception:
  126. pass
  127. # Search for dependencies of the given binaries
  128. return bindepend.Dependencies(binaries, redirects=binding_redirects, xtrapath=extra_libdirs)
  129. class Analysis(Target):
  130. """
  131. Class that performs analysis of the user's main Python scripts.
  132. An Analysis has five outputs, all TOCs (Table of Contents) accessed as attributes of the analysis.
  133. scripts
  134. The scripts you gave Analysis as input, with any runtime hook scripts prepended.
  135. pure
  136. The pure Python modules.
  137. binaries
  138. The extensionmodules and their dependencies. The secondary dependencies are filtered. On Windows files from
  139. C:\\Windows are excluded by default. On Linux/Unix only system libraries from /lib or /usr/lib are excluded.
  140. datas
  141. Data-file dependencies. These are data-file that are found to be needed by modules. They can be anything:
  142. plugins, font files, images, translations, etc.
  143. zipfiles
  144. The zipfiles dependencies (usually .egg files).
  145. """
  146. _old_scripts = {
  147. absnormpath(os.path.join(HOMEPATH, "support", "_mountzlib.py")),
  148. absnormpath(os.path.join(HOMEPATH, "support", "useUnicode.py")),
  149. absnormpath(os.path.join(HOMEPATH, "support", "useTK.py")),
  150. absnormpath(os.path.join(HOMEPATH, "support", "unpackTK.py")),
  151. absnormpath(os.path.join(HOMEPATH, "support", "removeTK.py"))
  152. }
  153. def __init__(
  154. self,
  155. scripts,
  156. pathex=None,
  157. binaries=None,
  158. datas=None,
  159. hiddenimports=None,
  160. hookspath=None,
  161. hooksconfig=None,
  162. excludes=None,
  163. runtime_hooks=None,
  164. cipher=None,
  165. win_no_prefer_redirects=False,
  166. win_private_assemblies=False,
  167. noarchive=False
  168. ):
  169. """
  170. scripts
  171. A list of scripts specified as file names.
  172. pathex
  173. An optional list of paths to be searched before sys.path.
  174. binaries
  175. An optional list of additional binaries (dlls, etc.) to include.
  176. datas
  177. An optional list of additional data files to include.
  178. hiddenimport
  179. An optional list of additional (hidden) modules to include.
  180. hookspath
  181. An optional list of additional paths to search for hooks. (hook-modules).
  182. hooksconfig
  183. An optional dict of config settings for hooks. (hook-modules).
  184. excludes
  185. An optional list of module or package names (their Python names, not path names) that will be
  186. ignored (as though they were not found).
  187. runtime_hooks
  188. An optional list of scripts to use as users' runtime hooks. Specified as file names.
  189. cipher
  190. Add optional instance of the pyz_crypto.PyiBlockCipher class (with a provided key).
  191. win_no_prefer_redirects
  192. If True, prefer not to follow version redirects when searching for Windows SxS Assemblies.
  193. win_private_assemblies
  194. If True, change all bundled Windows SxS Assemblies into Private Assemblies to enforce assembly versions.
  195. noarchive
  196. If True, do not place source files in a archive, but keep them as individual files.
  197. """
  198. super().__init__()
  199. from PyInstaller.config import CONF
  200. self.inputs = []
  201. spec_dir = os.path.dirname(CONF['spec'])
  202. for script in scripts:
  203. # If path is relative, it is relative to the location of .spec file.
  204. if not os.path.isabs(script):
  205. script = os.path.join(spec_dir, script)
  206. if absnormpath(script) in self._old_scripts:
  207. logger.warning('Ignoring obsolete auto-added script %s', script)
  208. continue
  209. # Normalize script path.
  210. script = os.path.normpath(script)
  211. if not os.path.exists(script):
  212. raise SystemExit("script '%s' not found" % script)
  213. self.inputs.append(script)
  214. # Django hook requires this variable to find the script manage.py.
  215. CONF['main_script'] = self.inputs[0]
  216. self.pathex = self._extend_pathex(pathex, self.inputs)
  217. # Set global config variable 'pathex' to make it available for PyInstaller.utils.hooks and import hooks. Path
  218. # extensions for module search.
  219. CONF['pathex'] = self.pathex
  220. # Extend sys.path so PyInstaller could find all necessary modules.
  221. logger.info('Extending PYTHONPATH with paths\n' + pprint.pformat(self.pathex))
  222. sys.path.extend(self.pathex)
  223. # If pkg_resources has already been imported, force update of its working set to account for changes made to
  224. # sys.path. Otherwise, distribution data in the added path(s) may not be discovered.
  225. if 'pkg_resources' in sys.modules:
  226. # See https://github.com/pypa/setuptools/issues/373
  227. import pkg_resources
  228. if hasattr(pkg_resources, '_initialize_master_working_set'):
  229. pkg_resources._initialize_master_working_set()
  230. # Set global variable to hold assembly binding redirects
  231. CONF['binding_redirects'] = []
  232. self.hiddenimports = hiddenimports or []
  233. # Include modules detected when parsing options, like 'codecs' and encodings.
  234. self.hiddenimports.extend(CONF['hiddenimports'])
  235. self.hookspath = []
  236. # Append directories in `hookspath` (`--additional-hooks-dir`) to take precedence over those from the entry
  237. # points.
  238. if hookspath:
  239. self.hookspath.extend(hookspath)
  240. # Add hook directories from PyInstaller entry points.
  241. self.hookspath += discover_hook_directories()
  242. self.hooksconfig = {}
  243. if hooksconfig:
  244. self.hooksconfig.update(hooksconfig)
  245. # Custom runtime hook files that should be included and started before any existing PyInstaller runtime hooks.
  246. self.custom_runtime_hooks = runtime_hooks or []
  247. if cipher:
  248. logger.info('Will encrypt Python bytecode with provided cipher key')
  249. # Create a Python module which contains the decryption key which will be used at runtime by
  250. # pyi_crypto.PyiBlockCipher.
  251. pyi_crypto_key_path = os.path.join(CONF['workpath'], 'pyimod00_crypto_key.py')
  252. with open(pyi_crypto_key_path, 'w', encoding='utf-8') as f:
  253. f.write('# -*- coding: utf-8 -*-\nkey = %r\n' % cipher.key)
  254. self.hiddenimports.append('tinyaes')
  255. self.excludes = excludes or []
  256. self.scripts = TOC()
  257. self.pure = TOC()
  258. self.binaries = TOC()
  259. self.zipfiles = TOC()
  260. self.zipped_data = TOC()
  261. self.datas = TOC()
  262. self.dependencies = TOC()
  263. self.binding_redirects = CONF['binding_redirects'] = []
  264. self.win_no_prefer_redirects = win_no_prefer_redirects
  265. self.win_private_assemblies = win_private_assemblies
  266. self._python_version = sys.version
  267. self.noarchive = noarchive
  268. self.__postinit__()
  269. # TODO: create a function to convert datas/binaries from 'hook format' to TOC.
  270. # Initialise 'binaries' and 'datas' with lists specified in .spec file.
  271. if binaries:
  272. logger.info("Appending 'binaries' from .spec")
  273. for name, pth in format_binaries_and_datas(binaries, workingdir=spec_dir):
  274. self.binaries.append((name, pth, 'BINARY'))
  275. if datas:
  276. logger.info("Appending 'datas' from .spec")
  277. for name, pth in format_binaries_and_datas(datas, workingdir=spec_dir):
  278. self.datas.append((name, pth, 'DATA'))
  279. _GUTS = ( # input parameters
  280. ('inputs', _check_guts_eq), # parameter `scripts`
  281. ('pathex', _check_guts_eq),
  282. ('hiddenimports', _check_guts_eq),
  283. ('hookspath', _check_guts_eq),
  284. ('hooksconfig', _check_guts_eq),
  285. ('excludes', _check_guts_eq),
  286. ('custom_runtime_hooks', _check_guts_eq),
  287. ('win_no_prefer_redirects', _check_guts_eq),
  288. ('win_private_assemblies', _check_guts_eq),
  289. ('noarchive', _check_guts_eq),
  290. # 'cipher': no need to check as it is implied by an additional hidden import
  291. # calculated/analysed values
  292. ('_python_version', _check_guts_eq),
  293. ('scripts', _check_guts_toc_mtime),
  294. ('pure', lambda *args: _check_guts_toc_mtime(*args, **{'pyc': 1})),
  295. ('binaries', _check_guts_toc_mtime),
  296. ('zipfiles', _check_guts_toc_mtime),
  297. ('zipped_data', None), # TODO check this, too
  298. ('datas', _check_guts_toc_mtime),
  299. # TODO: Need to add "dependencies"?
  300. # cached binding redirects - loaded into CONF for PYZ/COLLECT to find.
  301. ('binding_redirects', None),
  302. )
  303. def _extend_pathex(self, spec_pathex, scripts):
  304. """
  305. Normalize additional paths where PyInstaller will look for modules and add paths with scripts to the list of
  306. paths.
  307. :param spec_pathex: Additional paths defined defined in .spec file.
  308. :param scripts: Scripts to create executable from.
  309. :return: list of updated paths
  310. """
  311. # Based on main supplied script - add top-level modules directory to PYTHONPATH.
  312. # Sometimes the main app script is not top-level module but submodule like 'mymodule.mainscript.py'.
  313. # In that case PyInstaller will not be able find modules in the directory containing 'mymodule'.
  314. # Add this directory to PYTHONPATH so PyInstaller could find it.
  315. pathex = []
  316. # Add scripts paths first.
  317. for script in scripts:
  318. logger.debug('script: %s' % script)
  319. script_toplevel_dir = get_path_to_toplevel_modules(script)
  320. if script_toplevel_dir:
  321. pathex.append(script_toplevel_dir)
  322. # Append paths from .spec.
  323. if spec_pathex is not None:
  324. pathex.extend(spec_pathex)
  325. # Normalize paths in pathex and make them absolute.
  326. return [absnormpath(p) for p in pathex]
  327. def _check_guts(self, data, last_build):
  328. if Target._check_guts(self, data, last_build):
  329. return True
  330. for fnm in self.inputs:
  331. if mtime(fnm) > last_build:
  332. logger.info("Building because %s changed", fnm)
  333. return True
  334. # Now we know that none of the input parameters and none of the input files has changed. So take the values
  335. # calculated resp. analysed in the last run and store them in `self`.
  336. self.scripts = TOC(data['scripts'])
  337. self.pure = TOC(data['pure'])
  338. self.binaries = TOC(data['binaries'])
  339. self.zipfiles = TOC(data['zipfiles'])
  340. self.zipped_data = TOC(data['zipped_data'])
  341. self.datas = TOC(data['datas'])
  342. # Store previously found binding redirects in CONF for later use by PKG/COLLECT
  343. from PyInstaller.config import CONF
  344. self.binding_redirects = CONF['binding_redirects'] = data['binding_redirects']
  345. return False
  346. def assemble(self):
  347. """
  348. This method is the MAIN method for finding all necessary files to be bundled.
  349. """
  350. from PyInstaller.config import CONF
  351. for m in self.excludes:
  352. logger.debug("Excluding module '%s'" % m)
  353. self.graph = initialize_modgraph(excludes=self.excludes, user_hook_dirs=self.hookspath)
  354. # TODO: find a better place where to put 'base_library.zip' and when to created it.
  355. # For Python 3 it is necessary to create file 'base_library.zip' containing core Python modules. In Python 3
  356. # some built-in modules are written in pure Python. base_library.zip is a way how to have those modules as
  357. # "built-in".
  358. libzip_filename = os.path.join(CONF['workpath'], 'base_library.zip')
  359. create_py3_base_library(libzip_filename, graph=self.graph)
  360. # Bundle base_library.zip as data file.
  361. # Data format of TOC item: ('relative_path_in_dist_dir', 'absolute_path_on_disk', 'DATA')
  362. self.datas.append((os.path.basename(libzip_filename), libzip_filename, 'DATA'))
  363. # Expand sys.path of module graph. The attribute is the set of paths to use for imports: sys.path, plus our
  364. # loader, plus other paths from e.g. --path option).
  365. self.graph.path = self.pathex + self.graph.path
  366. self.graph.set_setuptools_nspackages()
  367. logger.info("running Analysis %s", self.tocbasename)
  368. # Get paths to Python and, in Windows, the manifest.
  369. python = compat.python_executable
  370. if not is_win:
  371. # Linux/MacOS: get a real, non-link path to the running Python executable.
  372. while os.path.islink(python):
  373. python = os.path.join(os.path.dirname(python), os.readlink(python))
  374. depmanifest = None
  375. else:
  376. # Windows: Create a manifest to embed into built .exe, containing the same dependencies as python.exe.
  377. depmanifest = winmanifest.Manifest(
  378. type_="win32",
  379. name=CONF['specnm'],
  380. processorArchitecture=winmanifest.processor_architecture(),
  381. version=(1, 0, 0, 0)
  382. )
  383. depmanifest.filename = os.path.join(CONF['workpath'], CONF['specnm'] + ".exe.manifest")
  384. # We record "binaries" separately from the modulegraph, as there is no way to record those dependencies in the
  385. # graph. These include the python executable and any binaries added by hooks later. "binaries" are not the same
  386. # as "extensions" which are .so or .dylib that are found and recorded as extension nodes in the graph. Reset
  387. # seen variable before running bindepend. We use bindepend only for the python executable.
  388. bindepend.seen.clear()
  389. # Add binary and assembly dependencies of Python.exe. This also ensures that its assembly dependencies under
  390. # Windows get added to the built .exe's manifest. Python 2.7 extension modules have no assembly dependencies,
  391. # and rely on the app-global dependencies set by the .exe.
  392. self.binaries.extend(
  393. bindepend.Dependencies([('', python, '')], manifest=depmanifest, redirects=self.binding_redirects)[1:]
  394. )
  395. if is_win:
  396. depmanifest.writeprettyxml()
  397. # -- Module graph. --
  398. #
  399. # Construct the module graph of import relationships between modules required by this user's application. For
  400. # each entry point (top-level user-defined Python script), all imports originating from this entry point are
  401. # recursively parsed into a subgraph of the module graph. This subgraph is then connected to this graph's root
  402. # node, ensuring imported module nodes will be reachable from the root node -- which is is (arbitrarily) chosen
  403. # to be the first entry point's node.
  404. # List to hold graph nodes of scripts and runtime hooks in use order.
  405. priority_scripts = []
  406. # Assume that if the script does not exist, Modulegraph will raise error. Save the graph nodes of each in
  407. # sequence.
  408. for script in self.inputs:
  409. logger.info("Analyzing %s", script)
  410. priority_scripts.append(self.graph.add_script(script))
  411. # Analyze the script's hidden imports (named on the command line)
  412. self.graph.add_hiddenimports(self.hiddenimports)
  413. # -- Post-graph hooks. --
  414. self.graph.process_post_graph_hooks(self)
  415. # Update 'binaries' TOC and 'datas' TOC.
  416. deps_proc = DependencyProcessor(self.graph, self.graph._additional_files_cache)
  417. self.binaries.extend(deps_proc.make_binaries_toc())
  418. self.datas.extend(deps_proc.make_datas_toc())
  419. self.zipped_data.extend(deps_proc.make_zipped_data_toc())
  420. # Note: zipped eggs are collected below
  421. # -- Look for dlls that are imported by Python 'ctypes' module. --
  422. # First get code objects of all modules that import 'ctypes'.
  423. logger.info('Looking for ctypes DLLs')
  424. # dict like: {'module1': code_obj, 'module2': code_obj}
  425. ctypes_code_objs = self.graph.get_code_using("ctypes")
  426. for name, co in ctypes_code_objs.items():
  427. # Get dlls that might be needed by ctypes.
  428. logger.debug('Scanning %s for shared libraries or dlls', name)
  429. try:
  430. ctypes_binaries = scan_code_for_ctypes(co)
  431. self.binaries.extend(set(ctypes_binaries))
  432. except Exception as ex:
  433. raise RuntimeError(f"Failed to scan the module '{name}'. " f"This is a bug. Please report it.") from ex
  434. self.datas.extend((dest, source, "DATA")
  435. for (dest, source) in format_binaries_and_datas(self.graph.metadata_required()))
  436. # Analyze run-time hooks. Run-time hooks has to be executed before user scripts. Add them to the beginning of
  437. # 'priority_scripts'.
  438. priority_scripts = self.graph.analyze_runtime_hooks(self.custom_runtime_hooks) + priority_scripts
  439. # 'priority_scripts' is now a list of the graph nodes of custom runtime hooks, then regular runtime hooks, then
  440. # the PyI loader scripts. Further on, we will make sure they end up at the front of self.scripts
  441. # -- Extract the nodes of the graph as TOCs for further processing. --
  442. # Initialize the scripts list with priority scripts in the proper order.
  443. self.scripts = self.graph.nodes_to_toc(priority_scripts)
  444. # Extend the binaries list with all the Extensions modulegraph has found.
  445. self.binaries = self.graph.make_binaries_toc(self.binaries)
  446. # Fill the "pure" list with pure Python modules.
  447. assert len(self.pure) == 0
  448. self.pure = self.graph.make_pure_toc()
  449. # And get references to module code objects constructed by ModuleGraph to avoid writing .pyc/pyo files to hdd.
  450. self.pure._code_cache = self.graph.get_code_objects()
  451. # Add remaining binary dependencies - analyze Python C-extensions and what DLLs they depend on.
  452. #
  453. # Up until this point, we did very best not to import the packages into the main process. However, a package
  454. # may set up additional library search paths during its import (e.g., by modifying PATH or calling the
  455. # add_dll_directory() function on Windows, or modifying LD_LIBRARY_PATH on Linux). In order to reliably
  456. # discover dynamic libraries, we therefore require an environment with all packages imported. We achieve that
  457. # by gathering list of all collected packages, and spawn an isolated process, in which we first import all
  458. # the packages from the list, and then perform search for dynamic libraries.
  459. logger.info('Looking for dynamic libraries')
  460. collected_packages = self.graph.get_collected_packages()
  461. self.binaries.extend(
  462. isolated.call(find_binary_dependencies, list(self.binaries), self.binding_redirects, collected_packages)
  463. )
  464. # Include zipped Python eggs.
  465. logger.info('Looking for eggs')
  466. self.zipfiles.extend(deps_proc.make_zipfiles_toc())
  467. # Verify that Python dynamic library can be found. Without dynamic Python library PyInstaller cannot continue.
  468. self._check_python_library(self.binaries)
  469. if is_win:
  470. # Remove duplicate redirects
  471. self.binding_redirects[:] = list(set(self.binding_redirects))
  472. logger.info("Found binding redirects: \n%s", self.binding_redirects)
  473. # Filter binaries to adjust path of extensions that come from python's lib-dynload directory. Prefix them with
  474. # lib-dynload so that we will collect them into subdirectory instead of directly into _MEIPASS
  475. for idx, tpl in enumerate(self.binaries):
  476. name, path, typecode = tpl
  477. if (
  478. typecode == 'EXTENSION' and not os.path.dirname(os.path.normpath(name))
  479. and os.path.basename(os.path.dirname(path)) == 'lib-dynload'
  480. ):
  481. name = os.path.join('lib-dynload', name)
  482. self.binaries[idx] = (name, path, typecode)
  483. # Place Python source in data files for the noarchive case.
  484. if self.noarchive:
  485. # Create a new TOC of ``(dest path for .pyc, source for .py, type)``.
  486. new_toc = TOC()
  487. for name, path, typecode in self.pure:
  488. assert typecode == 'PYMODULE'
  489. # Transform a python module name into a file name.
  490. name = name.replace('.', os.sep)
  491. # Special case: modules have an implied filename to add.
  492. if os.path.splitext(os.path.basename(path))[0] == '__init__':
  493. name += os.sep + '__init__'
  494. # Append the extension for the compiled result. In python 3.5 (PEP-488) .pyo files were replaced by
  495. # .opt-1.pyc and .opt-2.pyc. However, it seems that for bytecode-only module distribution, we always
  496. # need to use the .pyc extension.
  497. name += '.pyc'
  498. new_toc.append((name, path, typecode))
  499. # Put the result of byte-compiling this TOC in datas. Mark all entries as data.
  500. for name, path, typecode in compile_py_files(new_toc, CONF['workpath']):
  501. self.datas.append((name, path, 'DATA'))
  502. # Store no source in the archive.
  503. self.pure = TOC()
  504. # Write warnings about missing modules.
  505. self._write_warnings()
  506. # Write debug information about the graph
  507. self._write_graph_debug()
  508. def _write_warnings(self):
  509. """
  510. Write warnings about missing modules. Get them from the graph and use the graph to figure out who tried to
  511. import them.
  512. """
  513. def dependency_description(name, dep_info):
  514. if not dep_info or dep_info == 'direct':
  515. imptype = 0
  516. else:
  517. imptype = (dep_info.conditional + 2 * dep_info.function + 4 * dep_info.tryexcept)
  518. return '%s (%s)' % (name, IMPORT_TYPES[imptype])
  519. from PyInstaller.config import CONF
  520. miss_toc = self.graph.make_missing_toc()
  521. with open(CONF['warnfile'], 'w', encoding='utf-8') as wf:
  522. wf.write(WARNFILE_HEADER)
  523. for (n, p, status) in miss_toc:
  524. importers = self.graph.get_importers(n)
  525. print(
  526. status,
  527. 'module named',
  528. n,
  529. '- imported by',
  530. ', '.join(dependency_description(name, data) for name, data in importers),
  531. file=wf
  532. )
  533. logger.info("Warnings written to %s", CONF['warnfile'])
  534. def _write_graph_debug(self):
  535. """
  536. Write a xref (in html) and with `--log-level DEBUG` a dot-drawing of the graph.
  537. """
  538. from PyInstaller.config import CONF
  539. with open(CONF['xref-file'], 'w', encoding='utf-8') as fh:
  540. self.graph.create_xref(fh)
  541. logger.info("Graph cross-reference written to %s", CONF['xref-file'])
  542. if logger.getEffectiveLevel() > logging.DEBUG:
  543. return
  544. # The `DOT language's <https://www.graphviz.org/doc/info/lang.html>`_ default character encoding (see the end
  545. # of the linked page) is UTF-8.
  546. with open(CONF['dot-file'], 'w', encoding='utf-8') as fh:
  547. self.graph.graphreport(fh)
  548. logger.info("Graph drawing written to %s", CONF['dot-file'])
  549. def _check_python_library(self, binaries):
  550. """
  551. Verify presence of the Python dynamic library in the binary dependencies. Python library is an essential
  552. piece that has to be always included.
  553. """
  554. # First check that libpython is in resolved binary dependencies.
  555. for (nm, filename, typ) in binaries:
  556. if typ == 'BINARY' and nm in PYDYLIB_NAMES:
  557. # Just print its filename and return.
  558. logger.info('Using Python library %s', filename)
  559. # Checking was successful - end of function.
  560. return
  561. # Python lib not in dependencies - try to find it.
  562. logger.info('Python library not in binary dependencies. Doing additional searching...')
  563. python_lib = bindepend.get_python_library_path()
  564. logger.debug('Adding Python library to binary dependencies')
  565. binaries.append((os.path.basename(python_lib), python_lib, 'BINARY'))
  566. logger.info('Using Python library %s', python_lib)
  567. def exclude_system_libraries(self, list_of_exceptions=None):
  568. """
  569. This method may be optionally called from the spec file to exclude any system libraries from the list of
  570. binaries other than those containing the shell-style wildcards in list_of_exceptions. Those that match
  571. '*python*' or are stored under 'lib-dynload' are always treated as exceptions and not excluded.
  572. """
  573. self.binaries = [i for i in self.binaries if _should_include_system_binary(i, list_of_exceptions or [])]
  574. class ExecutableBuilder:
  575. """
  576. Class that constructs the executable.
  577. """
  578. # TODO wrap the 'main' and 'build' function into this class.
  579. def build(spec, distpath, workpath, clean_build):
  580. """
  581. Build the executable according to the created SPEC file.
  582. """
  583. from PyInstaller.config import CONF
  584. # Ensure starting tilde and environment variables get expanded in distpath / workpath.
  585. # '~/path/abc', '${env_var_name}/path/abc/def'
  586. distpath = os.path.abspath(compat.expand_path(distpath))
  587. workpath = os.path.abspath(compat.expand_path(workpath))
  588. CONF['spec'] = os.path.abspath(compat.expand_path(spec))
  589. CONF['specpath'], CONF['specnm'] = os.path.split(CONF['spec'])
  590. CONF['specnm'] = os.path.splitext(CONF['specnm'])[0]
  591. # Add 'specname' to workpath and distpath if they point to PyInstaller homepath.
  592. if os.path.dirname(distpath) == HOMEPATH:
  593. distpath = os.path.join(HOMEPATH, CONF['specnm'], os.path.basename(distpath))
  594. CONF['distpath'] = distpath
  595. if os.path.dirname(workpath) == HOMEPATH:
  596. workpath = os.path.join(HOMEPATH, CONF['specnm'], os.path.basename(workpath), CONF['specnm'])
  597. else:
  598. workpath = os.path.join(workpath, CONF['specnm'])
  599. CONF['workpath'] = workpath
  600. CONF['warnfile'] = os.path.join(workpath, 'warn-%s.txt' % CONF['specnm'])
  601. CONF['dot-file'] = os.path.join(workpath, 'graph-%s.dot' % CONF['specnm'])
  602. CONF['xref-file'] = os.path.join(workpath, 'xref-%s.html' % CONF['specnm'])
  603. # Clean PyInstaller cache (CONF['cachedir']) and temporary files (workpath) to be able start a clean build.
  604. if clean_build:
  605. logger.info('Removing temporary files and cleaning cache in %s', CONF['cachedir'])
  606. for pth in (CONF['cachedir'], workpath):
  607. if os.path.exists(pth):
  608. # Remove all files in 'pth'.
  609. for f in glob.glob(pth + '/*'):
  610. # Remove dirs recursively.
  611. if os.path.isdir(f):
  612. shutil.rmtree(f)
  613. else:
  614. os.remove(f)
  615. # Create DISTPATH and workpath if they does not exist.
  616. for pth in (CONF['distpath'], CONF['workpath']):
  617. os.makedirs(pth, exist_ok=True)
  618. # Construct NAMESPACE for running the Python code from .SPEC file.
  619. # NOTE: Passing NAMESPACE allows to avoid having global variables in this module and makes isolated environment for
  620. # running tests.
  621. # NOTE: Defining NAMESPACE allows to map any class to a apecific name for .SPEC.
  622. # FIXME: Some symbols might be missing. Add them if there are some failures.
  623. # TODO: What from this .spec API is deprecated and could be removed?
  624. spec_namespace = {
  625. # Set of global variables that can be used while processing .spec file. Some of them act as configuration
  626. # options.
  627. 'DISTPATH': CONF['distpath'],
  628. 'HOMEPATH': HOMEPATH,
  629. 'SPEC': CONF['spec'],
  630. 'specnm': CONF['specnm'],
  631. 'SPECPATH': CONF['specpath'],
  632. 'WARNFILE': CONF['warnfile'],
  633. 'workpath': CONF['workpath'],
  634. # PyInstaller classes for .spec.
  635. 'TOC': TOC,
  636. 'Analysis': Analysis,
  637. 'BUNDLE': BUNDLE,
  638. 'COLLECT': COLLECT,
  639. 'EXE': EXE,
  640. 'MERGE': MERGE,
  641. 'PYZ': PYZ,
  642. 'Tree': Tree,
  643. 'Splash': Splash,
  644. # Python modules available for .spec.
  645. 'os': os,
  646. 'pyi_crypto': pyz_crypto,
  647. }
  648. # Execute the specfile. Read it as a binary file...
  649. try:
  650. with open(spec, 'rb') as f:
  651. # ... then let Python determine the encoding, since ``compile`` accepts byte strings.
  652. code = compile(f.read(), spec, 'exec')
  653. except FileNotFoundError:
  654. raise SystemExit(f'Spec file "{spec}" not found!')
  655. exec(code, spec_namespace)
  656. def __add_options(parser):
  657. parser.add_argument(
  658. "--distpath",
  659. metavar="DIR",
  660. default=DEFAULT_DISTPATH,
  661. help="Where to put the bundled app (default: ./dist)",
  662. )
  663. parser.add_argument(
  664. '--workpath',
  665. default=DEFAULT_WORKPATH,
  666. help="Where to put all the temporary work files, .log, .pyz and etc. (default: ./build)",
  667. )
  668. parser.add_argument(
  669. '-y',
  670. '--noconfirm',
  671. action="store_true",
  672. default=False,
  673. help="Replace output directory (default: %s) without asking for confirmation" %
  674. os.path.join('SPECPATH', 'dist', 'SPECNAME'),
  675. )
  676. parser.add_argument(
  677. '--upx-dir',
  678. default=None,
  679. help="Path to UPX utility (default: search the execution path)",
  680. )
  681. parser.add_argument(
  682. "-a",
  683. "--ascii",
  684. action="store_true",
  685. help="Do not include unicode encoding support (default: included if available)",
  686. )
  687. parser.add_argument(
  688. '--clean',
  689. dest='clean_build',
  690. action='store_true',
  691. default=False,
  692. help="Clean PyInstaller cache and remove temporary files before building.",
  693. )
  694. def main(
  695. pyi_config,
  696. specfile,
  697. noconfirm=False,
  698. ascii=False,
  699. distpath=DEFAULT_DISTPATH,
  700. workpath=DEFAULT_WORKPATH,
  701. upx_dir=None,
  702. clean_build=False,
  703. **kw
  704. ):
  705. from PyInstaller.config import CONF
  706. CONF['noconfirm'] = noconfirm
  707. # Some modules are included if they are detected at build-time or if a command-line argument is specified
  708. # (e.g., --ascii).
  709. if CONF.get('hiddenimports') is None:
  710. CONF['hiddenimports'] = []
  711. # Test unicode support.
  712. if not ascii:
  713. CONF['hiddenimports'].extend(get_unicode_modules())
  714. # If configuration dict is supplied - skip configuration step.
  715. if pyi_config is None:
  716. import PyInstaller.configure as configure
  717. CONF.update(configure.get_config(upx_dir))
  718. else:
  719. CONF.update(pyi_config)
  720. if CONF['hasUPX']:
  721. setupUPXFlags()
  722. CONF['ui_admin'] = kw.get('ui_admin', False)
  723. CONF['ui_access'] = kw.get('ui_uiaccess', False)
  724. build(specfile, distpath, workpath, clean_build)