0
# Advanced Freezing
1
2
Direct access to cx_Freeze's core freezing engine provides programmatic control over module discovery, dependency analysis, and executable creation. This enables custom build workflows, integration with other tools, and fine-grained control over the freezing process.
3
4
## Capabilities
5
6
### Freezer Engine
7
8
The core Freezer class orchestrates the entire freezing process with platform-specific implementations and extensive configuration options.
9
10
```python { .api }
11
class Freezer:
12
"""Core freezing engine with platform-specific implementations."""
13
14
def __new__(
15
cls, *args, **kwargs
16
) -> WinFreezer | DarwinFreezer | LinuxFreezer:
17
"""Create appropriate platform-specific freezer instance."""
18
19
def __init__(
20
self,
21
executables: Sequence[Executable, Mapping[str, str], str],
22
constants_module: ConstantsModule | None = None,
23
includes: list[str] | None = None,
24
excludes: list[str] | None = None,
25
packages: list[str] | None = None,
26
replace_paths: list[str] | None = None,
27
compress: bool | None = True,
28
optimize: int = 0,
29
path: list[str | Path] | None = None,
30
target_dir: str | Path | None = None,
31
bin_includes: list[str] | None = None,
32
bin_excludes: list[str] | None = None,
33
bin_path_includes: list[str] | None = None,
34
bin_path_excludes: list[str] | None = None,
35
include_files: list[tuple[str, str]] | None = None,
36
zip_includes: list[tuple[str, str]] | None = None,
37
silent: bool | int = 0,
38
metadata: Any = None,
39
include_msvcr: bool = False,
40
include_msvcr_version: str | None = None,
41
zip_include_packages: Sequence[str] | None = None,
42
zip_exclude_packages: Sequence[str] | None = None,
43
zip_filename: Path | str | None = None,
44
):
45
"""
46
Initialize freezer with comprehensive configuration options.
47
48
Parameters:
49
- executables: List of Executable objects, dicts, or script strings
50
- constants_module: Custom constants module for frozen app
51
- includes: Modules to force include
52
- excludes: Modules to force exclude
53
- packages: Packages to include with all submodules
54
- replace_paths: Path replacements for included modules
55
- compress: Compress bytecode in zip archive
56
- optimize: Bytecode optimization level (0, 1, 2)
57
- path: Module search paths
58
- target_dir: Directory for built executables and dependent files
59
- bin_includes: Binary files to include
60
- bin_excludes: Binary files to exclude
61
- bin_path_includes: Binary search paths to include
62
- bin_path_excludes: Binary search paths to exclude
63
- include_files: Additional files to copy [(source, dest), ...]
64
- zip_includes: Files to include in zip [(source, archive_name), ...]
65
- silent: Suppress output during freezing (bool or int level)
66
- metadata: Custom metadata for frozen application
67
- include_msvcr: Include Microsoft Visual C++ runtime (Windows)
68
- include_msvcr_version: Specific MSVCR version to include (Windows)
69
- zip_include_packages: Packages to store in zip
70
- zip_exclude_packages: Packages to exclude from zip
71
- zip_filename: Custom zip filename
72
"""
73
```
74
75
### Module Discovery and Analysis
76
77
ModuleFinder provides the core module discovery engine that analyzes import dependencies and determines required modules.
78
79
```python { .api }
80
class ModuleFinder:
81
"""Discovers required modules through import analysis."""
82
83
def __init__(
84
self,
85
constants_module: ConstantsModule,
86
excludes: list[str] | None = None,
87
include_files: IncludesList | None = None,
88
path: list[str | Path] | None = None,
89
replace_paths: list[tuple[str, str]] | None = None,
90
zip_exclude_packages: Sequence[str] | None = None,
91
zip_include_packages: Sequence[str] | None = None,
92
zip_include_all_packages: bool = False,
93
zip_includes: IncludesList | None = None,
94
):
95
"""
96
Initialize module finder with search configuration.
97
98
Parameters:
99
- constants_module: Constants module for frozen application
100
- excludes: Modules to force exclude from discovery
101
- include_files: Additional files to include [(source, dest), ...]
102
- path: Module search paths
103
- replace_paths: Path replacements for included modules
104
- zip_exclude_packages: Packages to exclude from zip
105
- zip_include_packages: Packages to store in zip
106
- zip_include_all_packages: Store all packages in zip by default
107
- zip_includes: Files to include in zip [(source, archive_name), ...]
108
"""
109
110
def include_module(self, name: str) -> Module:
111
"""Force include a module by name."""
112
113
def exclude_module(self, name: str) -> None:
114
"""Force exclude a module by name."""
115
116
def include_package(self, name: str) -> None:
117
"""Include package with all submodules."""
118
119
def add_zip_file(self, filename: str) -> None:
120
"""Add zip file to module search path."""
121
122
def find_module(self, name: str, path: list[str] | None = None) -> Module:
123
"""Find and analyze a specific module."""
124
125
def load_module(
126
self,
127
name: str,
128
deferreds: list[str] | None = None,
129
parent: Module | None = None
130
) -> Module:
131
"""Load module and analyze its dependencies."""
132
133
@cached_property
134
def modules(self) -> list[Module]:
135
"""Get list of all discovered modules."""
136
137
@cached_property
138
def _modules(self) -> dict[str, Module]:
139
"""Internal module registry."""
140
```
141
142
### Module Representation
143
144
The Module class represents individual Python modules with their metadata, dependencies, and file information.
145
146
```python { .api }
147
class Module:
148
"""Represents a Python module in the frozen application."""
149
150
def __init__(
151
self,
152
name: str,
153
path: Sequence[Path | str] | None = None,
154
filename: Path | str | None = None,
155
parent: Module | None = None,
156
):
157
"""
158
Initialize module representation.
159
160
Parameters:
161
- name: Module name (dotted import name)
162
- path: Module search paths
163
- filename: Path to module file
164
- parent: Parent module for submodules/packages
165
"""
166
167
@property
168
def name(self) -> str:
169
"""Module name (dotted import name)."""
170
171
@property
172
def file(self) -> Path | None:
173
"""Path to module file."""
174
175
@property
176
def path(self) -> list[str]:
177
"""Module search path."""
178
179
@property
180
def code(self) -> CodeType | None:
181
"""Compiled module code object."""
182
183
@property
184
def parent(self) -> Module | None:
185
"""Parent module (for submodules)."""
186
187
@property
188
def distribution(self) -> DistributionCache | None:
189
"""Package distribution metadata."""
190
191
def in_file_system(self) -> int:
192
"""Check if module exists in filesystem (0=no, 1=yes, 2=namespace)."""
193
194
def store_in_file_system(self) -> bool:
195
"""Whether module should be stored as file vs in zip."""
196
```
197
198
### Constants Module
199
200
ConstantsModule provides a way to inject custom constants and configuration into frozen applications.
201
202
```python { .api }
203
class ConstantsModule:
204
"""Module for storing constants used by frozen executables."""
205
206
def __init__(self, release_string: str | None = None, constants: list = None):
207
"""
208
Initialize constants module.
209
210
Parameters:
211
- release_string: Version/release information
212
- constants: List of (name, value) tuples to inject
213
"""
214
215
@property
216
def values(self) -> dict[str, Any]:
217
"""Dictionary of constant name -> value mappings."""
218
219
def create(self, modules: dict[str, Module]) -> Module:
220
"""Create Module object containing the constants."""
221
```
222
223
### Platform-Specific Implementations
224
225
Freezer automatically creates platform-specific instances with specialized handling for each operating system.
226
227
```python { .api }
228
# Platform-specific freezer classes (internal)
229
class WinFreezer(Freezer):
230
"""Windows-specific freezing implementation."""
231
# Handles DLL dependencies, resource compilation, MSVCR inclusion
232
233
class DarwinFreezer(Freezer):
234
"""macOS-specific freezing implementation."""
235
# Handles framework bundling, library path fixing, code signing prep
236
237
class LinuxFreezer(Freezer):
238
"""Linux-specific freezing implementation."""
239
# Handles shared library dependencies, RPATH configuration
240
```
241
242
### Advanced Usage Examples
243
244
```python
245
from cx_Freeze import Freezer, Executable, ConstantsModule
246
247
# Custom constants injection
248
constants = ConstantsModule(
249
release_string="MyApp v1.0.0",
250
constants=[
251
("BUILD_TIME", "2024-01-15"),
252
("DEBUG_MODE", False),
253
("API_ENDPOINT", "https://api.example.com")
254
]
255
)
256
257
# Advanced freezer configuration
258
freezer = Freezer(
259
executables=[
260
Executable("main.py", base="gui", icon="app.ico"),
261
Executable("cli.py", base="console", target_name="mytool")
262
],
263
constants_module=constants,
264
includes=["tkinter", "sqlite3", "json"],
265
excludes=["unittest", "doctest", "pdb"],
266
packages=["requests", "numpy.core"],
267
replace_paths=[
268
("C:\\dev\\myapp", "/app"),
269
("/usr/local/lib/python3.x", "/lib")
270
],
271
include_files=[
272
("data/config.ini", "config.ini"),
273
("resources/", "resources/"),
274
("README.txt", "README.txt")
275
],
276
zip_includes=[
277
("templates/", "templates/"),
278
("static/", "static/")
279
],
280
zip_include_packages=["jinja2", "markupsafe"],
281
bin_excludes=["libc.so*", "libX11*"],
282
metadata={
283
"author": "Your Name",
284
"version": "1.0.0",
285
"description": "My Application"
286
},
287
optimize=2,
288
compress=True,
289
silent=False
290
)
291
292
# Execute freezing process
293
freezer.freeze()
294
```
295
296
### Module Hook System
297
298
cx_Freeze includes an extensive hook system for handling special requirements of popular packages.
299
300
```python { .api }
301
# Hook system integration (automatic)
302
# Hooks located in cx_Freeze.hooks package
303
304
# Available hooks for major packages:
305
hooks = [
306
"tkinter", "PyQt5", "PyQt6", "PySide2", "PySide6",
307
"numpy", "scipy", "pandas", "matplotlib", "sklearn",
308
"cv2", "PIL", "tensorflow", "torch", "requests",
309
# ... 60+ hooks total
310
]
311
312
# Custom hook development
313
def load_my_package(finder, module):
314
"""Custom hook for handling special package requirements."""
315
finder.include_module("my_package.submodule")
316
finder.add_zip_file("my_package_data.zip")
317
```
318
319
### Binary Dependency Management
320
321
Advanced control over binary dependencies and shared libraries.
322
323
```python { .api }
324
# Binary handling options
325
bin_includes = [
326
"libspecial.so", # Specific library
327
"custom.dll", # Windows DLL
328
"framework.dylib" # macOS library
329
]
330
331
bin_excludes = [
332
"libc.so*", # Exclude system libraries
333
"kernel32.dll", # Windows system DLLs
334
"libX11*" # X11 libraries
335
]
336
337
bin_path_includes = [
338
"/opt/custom/lib", # Custom library paths
339
"C:\\Program Files\\MyLib" # Windows library paths
340
]
341
342
bin_path_excludes = [
343
"/usr/lib/python*/lib-dynload", # Python stdlib extensions
344
"/System/Library" # macOS system libraries
345
]
346
```
347
348
### Error Handling and Debugging
349
350
Advanced freezing provides detailed error reporting and debugging capabilities.
351
352
```python { .api }
353
# Exception types for advanced freezing
354
class ModuleError(Exception):
355
"""Module loading or metadata errors."""
356
357
class FileError(Exception):
358
"""File or resource not found errors."""
359
360
class OptionError(Exception):
361
"""Configuration or option errors."""
362
363
# Debugging and introspection
364
freezer = Freezer(executables=[], silent=False)
365
366
# Access internal state
367
modules = freezer.finder.modules # All discovered modules
368
missing = freezer.finder.bad_modules # Failed module imports
369
excluded = freezer.finder.excluded_modules # Explicitly excluded
370
371
# Platform-specific debugging
372
if hasattr(freezer, 'get_dependent_files'): # Windows
373
deps = freezer.get_dependent_files("myapp.exe")
374
375
# Module analysis
376
for module in modules:
377
print(f"Module: {module.name}")
378
print(f" File: {module.file}")
379
print(f" In filesystem: {module.in_file_system()}")
380
print(f" Store in filesystem: {module.store_in_file_system()}")
381
```
382
383
### Integration with Build Systems
384
385
Advanced freezing can be integrated with custom build systems and workflows.
386
387
```python
388
import os
389
import sys
390
from pathlib import Path
391
from cx_Freeze import Freezer, Executable
392
393
def custom_build_workflow():
394
"""Custom build workflow with pre/post processing."""
395
396
# Pre-processing
397
print("Preparing build environment...")
398
os.makedirs("dist", exist_ok=True)
399
400
# Custom executable configuration
401
exe = Executable(
402
script="main.py",
403
base="gui" if "--gui" in sys.argv else "console",
404
icon=find_best_icon(),
405
target_name=get_version_name()
406
)
407
408
# Advanced freezer setup
409
freezer = Freezer(
410
executables=[exe],
411
includes=get_required_modules(),
412
exclude=get_excluded_modules(),
413
include_files=collect_data_files(),
414
optimize=2 if "--release" in sys.argv else 0,
415
silent="--verbose" not in sys.argv
416
)
417
418
# Execute freezing
419
print("Freezing application...")
420
freezer.freeze()
421
422
# Post-processing
423
print("Finalizing build...")
424
sign_executables("dist/")
425
create_checksums("dist/")
426
427
print("Build complete!")
428
429
def find_best_icon():
430
"""Find appropriate icon for platform."""
431
platform_icons = {
432
"win32": "app.ico",
433
"darwin": "app.icns",
434
"linux": "app.png"
435
}
436
return platform_icons.get(sys.platform, "app.png")
437
```