0
# Spec File Classes
1
2
PyInstaller's spec file classes provide programmatic control over the build process. These classes define the dependency analysis, archive creation, and executable generation phases, allowing for complex customization beyond what's possible with command-line options.
3
4
## Capabilities
5
6
### Analysis Class
7
8
The Analysis class performs dependency analysis of Python scripts, collecting all required modules, binaries, and data files.
9
10
```python { .api }
11
class Analysis:
12
"""
13
Performs analysis of Python scripts and their dependencies.
14
15
The Analysis class discovers all modules, binaries, and data files
16
required by the application through import analysis and hook execution.
17
"""
18
19
def __init__(self, scripts, pathex=[], binaries=[], datas=[],
20
hiddenimports=[], hookspath=[], hooksconfig={},
21
runtime_hooks=[], excludes=[], win_no_prefer_redirects=False,
22
win_private_assemblies=False, cipher=None, noarchive=False,
23
module_collection_mode={}, optimize=-1):
24
"""
25
Initialize Analysis instance.
26
27
Args:
28
scripts (list): List of main script file paths to analyze
29
pathex (list): Additional paths to search before sys.path
30
binaries (list): Additional binaries as (src, dest) tuples
31
datas (list): Additional data files as (src, dest) tuples
32
hiddenimports (list): Hidden module names to force include
33
hookspath (list): Additional directories to search for hooks
34
hooksconfig (dict): Configuration dictionary for hooks
35
runtime_hooks (list): Runtime hook script paths
36
excludes (list): Module names to exclude from analysis
37
win_no_prefer_redirects (bool): Windows redirect handling
38
win_private_assemblies (bool): Windows assembly handling
39
cipher (deprecated): Previously used for encryption
40
noarchive (bool): Keep files as individual files instead of archive
41
module_collection_mode (dict): Per-module collection mode settings
42
optimize (int): Python bytecode optimization level (-1, 0, 1, 2)
43
"""
44
45
# Key attributes available after analysis:
46
scripts: list # Scripts with runtime hooks prepended
47
pure: list # Pure Python modules TOC
48
binaries: list # Extension modules and shared libraries TOC
49
datas: list # Data files TOC
50
zipfiles: list # Deprecated (always empty)
51
zipped_data: list # Deprecated (always empty)
52
```
53
54
#### Analysis Usage Example
55
56
```python
57
# Basic analysis
58
a = Analysis(
59
['main.py'],
60
pathex=['/extra/path'],
61
binaries=[('mylib.so', '.')],
62
datas=[('config/', 'config/')],
63
hiddenimports=['scipy.special'],
64
excludes=['matplotlib'],
65
optimize=0
66
)
67
68
# Analysis with hooks configuration
69
a = Analysis(
70
['app.py'],
71
hooksconfig={
72
'gi': {
73
'icons': ['Adwaita'],
74
'themes': ['Adwaita'],
75
'languages': ['en_US', 'de_DE']
76
}
77
}
78
)
79
```
80
81
### PYZ Class
82
83
Creates a zlib-compressed archive containing compiled Python modules.
84
85
```python { .api }
86
class PYZ:
87
"""
88
Creates a zlib-based PYZ archive containing byte-compiled Python modules.
89
90
The PYZ archive contains all pure Python modules collected during analysis,
91
compressed for efficient storage and fast loading at runtime.
92
"""
93
94
def __init__(self, *tocs, name=None):
95
"""
96
Initialize PYZ archive.
97
98
Args:
99
*tocs: One or more Table of Contents lists (typically Analysis.pure)
100
name (str, optional): Custom filename for .pyz archive
101
"""
102
103
# Attributes:
104
name: str # Archive filename
105
dependencies: list # Bootstrap dependencies
106
```
107
108
#### PYZ Usage Example
109
110
```python
111
# Standard PYZ creation
112
pyz = PYZ(a.pure, a.zipped_data)
113
114
# Custom PYZ name
115
pyz = PYZ(a.pure, name='myapp.pyz')
116
```
117
118
### PKG Class
119
120
Creates a CArchive package containing all collected files and dependencies.
121
122
```python { .api }
123
class PKG:
124
"""
125
Creates CArchive package containing all collected files.
126
127
The PKG contains binaries, data files, and the PYZ archive,
128
providing the complete application bundle for the executable.
129
"""
130
131
def __init__(self, toc, name=None, cdict=None, exclude_binaries=0,
132
strip_binaries=False, upx_binaries=False, upx_exclude=[]):
133
"""
134
Initialize PKG archive.
135
136
Args:
137
toc: Table of contents from Analysis or COLLECT
138
name (str, optional): Package name
139
cdict (dict, optional): Code dictionary for optimization
140
exclude_binaries (int): Exclude binary files (0=include, 1=exclude)
141
strip_binaries (bool): Strip debug symbols from binaries
142
upx_binaries (bool): Compress binaries with UPX
143
upx_exclude (list): Patterns for UPX exclusion
144
"""
145
```
146
147
### EXE Class
148
149
Creates the final executable from PKG and bootloader.
150
151
```python { .api }
152
class EXE:
153
"""
154
Creates final executable from PKG and bootloader.
155
156
The EXE class combines the application package with the appropriate
157
bootloader to create a standalone executable file.
158
"""
159
160
def __init__(self, *args, name='', console=True, debug=False,
161
bootloader_ignore_signals=False, strip=False, upx=True,
162
upx_exclude=[], runtime_tmpdir=None, contents_directory=None,
163
uac_admin=False, uac_uiaccess=False, win_no_prefer_redirects=False,
164
win_private_assemblies=False, embed_manifest=True, resources=[],
165
icon=None, version=None, disable_windowed_traceback=False,
166
argv_emulation=False, target_arch=None, codesign_identity=None,
167
entitlements_file=None, strictArchitecture=True):
168
"""
169
Initialize EXE instance.
170
171
Args:
172
*args: PKG instance and other dependencies
173
name (str): Executable name
174
console (bool): Console application (True) vs windowed (False)
175
debug (bool): Include debug information
176
bootloader_ignore_signals (bool): Bootloader signal handling
177
strip (bool): Strip debug symbols from executable
178
upx (bool): Compress executable with UPX
179
upx_exclude (list): UPX exclusion patterns
180
runtime_tmpdir (str): Runtime temporary directory path
181
contents_directory (str): Contents directory name for onedir
182
uac_admin (bool): Windows UAC admin execution level
183
uac_uiaccess (bool): Windows UAC UI access permissions
184
win_no_prefer_redirects (bool): Windows DLL redirect preferences
185
win_private_assemblies (bool): Windows private assembly handling
186
embed_manifest (bool): Embed Windows manifest in executable
187
resources (list): Additional Windows resources
188
icon (str): Application icon file path (.ico, .icns)
189
version (str): Version resource file path (Windows)
190
disable_windowed_traceback (bool): Disable traceback in windowed mode
191
argv_emulation (bool): macOS argv emulation for drag-and-drop
192
target_arch (str): Target architecture (x86_64, arm64, universal2)
193
codesign_identity (str): macOS code signing identity
194
entitlements_file (str): macOS entitlements file path
195
strictArchitecture (bool): macOS strict architecture enforcement
196
"""
197
```
198
199
#### EXE Usage Examples
200
201
```python
202
# One-file executable
203
exe = EXE(
204
pyz,
205
a.scripts,
206
a.binaries,
207
a.zipfiles,
208
a.datas,
209
[],
210
name='MyApp',
211
debug=False,
212
bootloader_ignore_signals=False,
213
strip=False,
214
upx=True,
215
console=True
216
)
217
218
# Windows executable with icon and version
219
exe = EXE(
220
pyz,
221
a.scripts,
222
a.binaries,
223
a.zipfiles,
224
a.datas,
225
[],
226
name='MyApp',
227
console=False,
228
icon='app.ico',
229
version='version_info.txt',
230
uac_admin=True
231
)
232
233
# macOS application
234
exe = EXE(
235
pyz,
236
a.scripts,
237
exclude_binaries=True,
238
name='MyApp',
239
debug=False,
240
console=False,
241
icon='app.icns',
242
codesign_identity='Developer ID Application: My Name',
243
entitlements_file='entitlements.plist'
244
)
245
```
246
247
### COLLECT Class
248
249
Collects files into a directory structure for onedir distribution.
250
251
```python { .api }
252
class COLLECT:
253
"""
254
Collects files into directory structure for onedir distribution.
255
256
COLLECT creates a directory containing the executable and all
257
its dependencies, providing a complete application folder.
258
"""
259
260
def __init__(self, *args, name='', strip_binaries=False,
261
upx_binaries=False, upx_exclude=[]):
262
"""
263
Initialize COLLECT instance.
264
265
Args:
266
*args: Target instances (EXE, PYZ) or TOC lists to collect
267
name (str): Output directory name
268
strip_binaries (bool): Strip debug symbols from binaries
269
upx_binaries (bool): Compress binaries with UPX
270
upx_exclude (list): UPX exclusion patterns
271
"""
272
```
273
274
#### COLLECT Usage Example
275
276
```python
277
# Create onedir distribution
278
coll = COLLECT(
279
exe,
280
a.binaries,
281
a.zipfiles,
282
a.datas,
283
strip_binaries=False,
284
upx_binaries=False,
285
name='MyApp'
286
)
287
```
288
289
### MERGE Class
290
291
Merges multiple Analysis instances for multi-program bundles.
292
293
```python { .api }
294
class MERGE:
295
"""
296
Merges multiple Analysis instances for multi-program bundles.
297
298
MERGE allows creating a single distribution containing multiple
299
executables that share common dependencies.
300
"""
301
302
def __init__(self, *args):
303
"""
304
Initialize MERGE instance.
305
306
Args:
307
*args: Dependencies as (analysis, script_name, executable_name) tuples
308
"""
309
```
310
311
#### MERGE Usage Example
312
313
```python
314
# Create separate analyses for each program
315
a1 = Analysis(['prog1.py'], ...)
316
a2 = Analysis(['prog2.py'], ...)
317
318
# Merge analyses
319
merge = MERGE(
320
(a1, 'prog1', 'Program1'),
321
(a2, 'prog2', 'Program2')
322
)
323
324
# Create executables from merged analysis
325
exe1 = EXE(PYZ(merge.pure), merge.scripts[0], ...)
326
exe2 = EXE(PYZ(merge.pure), merge.scripts[1], ...)
327
```
328
329
## Complete Spec File Example
330
331
```python
332
# myapp.spec - Complete spec file example
333
from PyInstaller.building.build_main import Analysis
334
from PyInstaller.building.api import PYZ, EXE, COLLECT
335
336
# Analysis phase
337
a = Analysis(
338
['src/main.py'],
339
pathex=['src'],
340
binaries=[],
341
datas=[
342
('config/', 'config/'),
343
('assets/', 'assets/'),
344
],
345
hiddenimports=[
346
'pkg_resources.py2_warn',
347
'sklearn.utils._cython_blas'
348
],
349
hookspath=['hooks'],
350
hooksconfig={},
351
runtime_hooks=['runtime_hooks/matplotlib_hook.py'],
352
excludes=['matplotlib', 'tkinter'],
353
win_no_prefer_redirects=False,
354
win_private_assemblies=False,
355
cipher=None,
356
noarchive=False,
357
optimize=0
358
)
359
360
# PYZ archive creation
361
pyz = PYZ(a.pure, a.zipped_data, cipher=None)
362
363
# Executable creation
364
exe = EXE(
365
pyz,
366
a.scripts,
367
a.binaries,
368
a.zipfiles,
369
a.datas,
370
[],
371
name='MyApplication',
372
debug=False,
373
bootloader_ignore_signals=False,
374
strip=False,
375
upx=True,
376
upx_exclude=[],
377
runtime_tmpdir=None,
378
console=True,
379
disable_windowed_traceback=False,
380
argv_emulation=False,
381
target_arch=None,
382
codesign_identity=None,
383
entitlements_file=None,
384
icon='assets/icon.ico'
385
)
386
387
# Optional: Create onedir distribution
388
coll = COLLECT(
389
exe,
390
a.binaries,
391
a.zipfiles,
392
a.datas,
393
strip_binaries=False,
394
upx_binaries=False,
395
name='MyApplication'
396
)
397
```
398
399
## Build Execution
400
401
After creating a .spec file:
402
403
```bash
404
# Build from spec file
405
pyinstaller myapp.spec
406
407
# Clean build
408
pyinstaller --clean myapp.spec
409
410
# Debug build
411
pyinstaller --log-level DEBUG myapp.spec
412
```