build_main.py 34 KB

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