build_main.py 35 KB

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