0
# Configuration & Options
1
2
Nuitka's configuration system provides comprehensive control over compilation behavior through command-line argument parsing and programmatic option management. The Options module handles all compilation settings from basic modes to advanced optimization controls.
3
4
## Capabilities
5
6
### Argument Parsing
7
8
Core functions for processing command-line arguments and configuration.
9
10
```python { .api }
11
def parseArgs():
12
"""
13
Parse and validate command line arguments.
14
15
Processes sys.argv to extract compilation options, validates argument
16
combinations, and configures internal compilation settings. Handles
17
all supported command-line flags and options.
18
19
Returns:
20
None: Options are stored in module-level state
21
22
Raises:
23
SystemExit: On invalid arguments or help requests
24
ArgumentError: On conflicting or invalid option combinations
25
"""
26
27
def commentArgs():
28
"""
29
Process and comment on parsed arguments.
30
31
Validates parsed arguments for consistency, applies defaults,
32
and provides warnings or information about argument interactions.
33
Must be called after parseArgs().
34
35
Returns:
36
None: Modifies internal option state
37
38
Raises:
39
ConfigurationError: On invalid option combinations
40
"""
41
```
42
43
**Usage Example:**
44
45
```python
46
import sys
47
from nuitka import Options
48
49
# Set command line arguments programmatically
50
sys.argv = [
51
"nuitka",
52
"--standalone",
53
"--plugin-enable=numpy",
54
"--verbose",
55
"myapp.py"
56
]
57
58
# Parse and validate arguments
59
Options.parseArgs()
60
Options.commentArgs()
61
62
print("Options parsed and validated successfully")
63
```
64
65
### Output Mode Detection
66
67
Functions to determine the compilation output mode and format.
68
69
```python { .api }
70
def isVerbose() -> bool:
71
"""
72
Check if verbose output mode is enabled.
73
74
Returns:
75
bool: True if verbose logging is enabled
76
"""
77
78
def shallTraceExecution() -> bool:
79
"""
80
Check if execution tracing is enabled.
81
82
Returns:
83
bool: True if runtime execution tracing is enabled
84
"""
85
86
def shallMakeModule() -> bool:
87
"""
88
Check if compiling as extension module.
89
90
Returns:
91
bool: True if creating C extension module (.so/.pyd)
92
"""
93
94
def shallMakePackage() -> bool:
95
"""
96
Check if compiling as package.
97
98
Returns:
99
bool: True if compiling Python package with multiple modules
100
"""
101
102
def shallMakeDll() -> bool:
103
"""
104
Check if creating DLL output.
105
106
Returns:
107
bool: True if creating dynamic library
108
"""
109
110
def shallMakeExe() -> bool:
111
"""
112
Check if creating executable output.
113
114
Returns:
115
bool: True if creating standalone executable
116
"""
117
```
118
119
**Usage Example:**
120
121
```python
122
from nuitka import Options
123
124
# After parsing arguments, check compilation mode
125
Options.parseArgs()
126
Options.commentArgs()
127
128
if Options.shallMakeModule():
129
print("Compiling as extension module")
130
elif Options.shallMakeExe():
131
print("Creating executable")
132
elif Options.shallMakePackage():
133
print("Compiling package")
134
135
if Options.isVerbose():
136
print("Verbose output enabled")
137
```
138
139
### Module and Package Inclusion
140
141
Functions to manage which modules and packages are included in compilation.
142
143
```python { .api }
144
def getMustIncludeModules() -> list:
145
"""
146
Get list of modules that must be included.
147
148
Returns explicitly specified modules that should be included
149
in the compilation regardless of automatic detection.
150
151
Returns:
152
list: Module names to forcibly include
153
"""
154
155
def getMustIncludePackages() -> list:
156
"""
157
Get list of packages that must be included.
158
159
Returns explicitly specified packages that should be included
160
in the compilation with all their submodules.
161
162
Returns:
163
list: Package names to forcibly include
164
"""
165
166
def getOutputFilename() -> str:
167
"""
168
Get the output filename or path.
169
170
Returns the target filename for the compiled output,
171
handling different compilation modes and extensions.
172
173
Returns:
174
str: Output filename or path
175
"""
176
177
def getPositionalArgs() -> list:
178
"""
179
Get positional command line arguments.
180
181
Returns the positional arguments passed to Nuitka,
182
typically the source files to compile.
183
184
Returns:
185
list: Positional argument strings
186
"""
187
188
def getMainArgs() -> list:
189
"""
190
Get main script arguments.
191
192
Returns arguments that should be passed to the main
193
script when using multiple main entry points.
194
195
Returns:
196
list: Main script arguments
197
"""
198
199
def getJobLimit() -> int:
200
"""
201
Get maximum number of parallel compilation jobs.
202
203
Returns the limit on parallel C compilation jobs,
204
useful for controlling resource usage.
205
206
Returns:
207
int: Maximum parallel jobs (default based on CPU count)
208
"""
209
210
def isDebugMode() -> bool:
211
"""
212
Check if debug mode is enabled.
213
214
Returns:
215
bool: True if debug information should be included
216
"""
217
218
def isStandaloneMode() -> bool:
219
"""
220
Check if standalone compilation mode is enabled.
221
222
Returns:
223
bool: True if creating standalone executable
224
"""
225
226
def isOnefileMode() -> bool:
227
"""
228
Check if onefile mode is enabled.
229
230
Returns:
231
bool: True if creating single-file executable
232
"""
233
234
def getPluginsEnabled() -> list:
235
"""
236
Get list of enabled plugins.
237
238
Returns all plugins that have been explicitly enabled
239
for the compilation process.
240
241
Returns:
242
list: Plugin names that are enabled
243
"""
244
245
def shallFollowStandardLibrary() -> bool:
246
"""
247
Check if standard library should be followed.
248
249
Returns:
250
bool: True if standard library modules should be included
251
"""
252
```
253
254
**Usage Example:**
255
256
```python
257
from nuitka import Options
258
259
Options.parseArgs()
260
Options.commentArgs()
261
262
# Get inclusion lists
263
required_modules = Options.getMustIncludeModules()
264
required_packages = Options.getMustIncludePackages()
265
266
print(f"Required modules: {required_modules}")
267
print(f"Required packages: {required_packages}")
268
```
269
270
## Configuration Categories
271
272
### Basic Compilation Options
273
274
Core options that control fundamental compilation behavior.
275
276
```python
277
import sys
278
from nuitka import Options
279
280
# Basic standalone compilation
281
sys.argv = ["nuitka", "--standalone", "app.py"]
282
Options.parseArgs()
283
284
# Module compilation
285
sys.argv = ["nuitka", "--module", "extension.py"]
286
Options.parseArgs()
287
288
# Package compilation
289
sys.argv = ["nuitka", "--package", "mypackage/"]
290
Options.parseArgs()
291
```
292
293
### Optimization Options
294
295
Configure various optimization levels and techniques.
296
297
```python
298
# Enable optimizations
299
sys.argv = [
300
"nuitka",
301
"--standalone",
302
"--optimize", # Enable C-level optimizations
303
"--lto=yes", # Link-time optimization
304
"--jobs=4", # Parallel compilation
305
"app.py"
306
]
307
308
Options.parseArgs()
309
Options.commentArgs()
310
311
# Check if optimizations are enabled
312
# Note: These would be internal option checks
313
```
314
315
### Debug and Development Options
316
317
Options for debugging and development workflows.
318
319
```python
320
# Debug configuration
321
sys.argv = [
322
"nuitka",
323
"--standalone",
324
"--debug", # Include debug information
325
"--verbose", # Verbose output
326
"--show-modules", # Show included modules
327
"--show-progress", # Show compilation progress
328
"app.py"
329
]
330
331
Options.parseArgs()
332
333
if Options.isVerbose():
334
print("Debug mode enabled with verbose output")
335
```
336
337
### Plugin Configuration
338
339
Configure plugin system and third-party package handling.
340
341
```python
342
# Plugin configuration
343
sys.argv = [
344
"nuitka",
345
"--standalone",
346
"--plugin-enable=numpy", # Enable NumPy plugin
347
"--plugin-enable=tk-inter", # Enable Tkinter plugin
348
"--plugin-enable=qt-plugins", # Enable Qt plugins
349
"app.py"
350
]
351
352
Options.parseArgs()
353
Options.commentArgs()
354
```
355
356
### Include and Exclude Options
357
358
Control what gets included in or excluded from compilation.
359
360
```python
361
# Inclusion/exclusion configuration
362
sys.argv = [
363
"nuitka",
364
"--standalone",
365
"--include-module=ssl", # Force include SSL module
366
"--include-package=requests", # Include requests package
367
"--include-data-files=config.json", # Include data files
368
"--exclude-module=test", # Exclude test modules
369
"app.py"
370
]
371
372
Options.parseArgs()
373
Options.commentArgs()
374
375
# Check what's included
376
modules = Options.getMustIncludeModules()
377
packages = Options.getMustIncludePackages()
378
```
379
380
## Advanced Configuration
381
382
### Programmatic Option Setting
383
384
Set options programmatically without command-line arguments.
385
386
```python
387
from nuitka import Options
388
import sys
389
390
class CompilationConfig:
391
"""Helper class for programmatic configuration."""
392
393
def __init__(self):
394
self.options = []
395
396
def standalone(self):
397
"""Enable standalone mode."""
398
self.options.append("--standalone")
399
return self
400
401
def module(self):
402
"""Enable module mode."""
403
self.options.append("--module")
404
return self
405
406
def include_package(self, package):
407
"""Include a package."""
408
self.options.append(f"--include-package={package}")
409
return self
410
411
def plugin(self, plugin_name):
412
"""Enable a plugin."""
413
self.options.append(f"--plugin-enable={plugin_name}")
414
return self
415
416
def verbose(self):
417
"""Enable verbose output."""
418
self.options.append("--verbose")
419
return self
420
421
def compile(self, source_file):
422
"""Execute compilation with configured options."""
423
sys.argv = ["nuitka"] + self.options + [source_file]
424
Options.parseArgs()
425
Options.commentArgs()
426
return self
427
428
# Usage
429
config = CompilationConfig()
430
config.standalone().include_package("numpy").plugin("numpy").verbose()
431
config.compile("myapp.py")
432
```
433
434
### Option Validation and Compatibility
435
436
Validate option combinations and check compatibility.
437
438
```python
439
from nuitka import Options
440
441
def validate_options():
442
"""Validate current option configuration."""
443
try:
444
Options.parseArgs()
445
Options.commentArgs()
446
447
# Check for incompatible combinations
448
if Options.shallMakeModule() and Options.shallMakeExe():
449
raise ValueError("Cannot create both module and executable")
450
451
# Validate plugin requirements
452
if Options.isVerbose():
453
print("Option validation passed")
454
455
return True
456
457
except Exception as e:
458
print(f"Option validation failed: {e}")
459
return False
460
```
461
462
### Dynamic Configuration
463
464
Modify configuration based on runtime conditions.
465
466
```python
467
import platform
468
from nuitka import Options
469
470
def configure_platform_specific():
471
"""Configure options based on platform."""
472
base_options = ["nuitka", "--standalone", "app.py"]
473
474
# Platform-specific options
475
if platform.system() == "Windows":
476
base_options.extend([
477
"--windows-disable-console",
478
"--windows-icon=icon.ico"
479
])
480
elif platform.system() == "Darwin": # macOS
481
base_options.extend([
482
"--macos-create-app-bundle",
483
"--macos-sign-identity=Developer ID"
484
])
485
elif platform.system() == "Linux":
486
base_options.extend([
487
"--linux-onefile-icon=icon.png"
488
])
489
490
sys.argv = base_options
491
Options.parseArgs()
492
Options.commentArgs()
493
```
494
495
## Environment Integration
496
497
### Environment Variable Support
498
499
Nuitka respects various environment variables for configuration.
500
501
```python
502
import os
503
from nuitka import Options
504
505
# Set environment variables before parsing
506
os.environ["NUITKA_CACHE_DIR"] = "/tmp/nuitka-cache"
507
os.environ["CC"] = "gcc"
508
os.environ["CXX"] = "g++"
509
510
# Parse options with environment context
511
Options.parseArgs()
512
Options.commentArgs()
513
```
514
515
### Configuration Files
516
517
While Nuitka primarily uses command-line options, you can create configuration management:
518
519
```python
520
import json
521
from nuitka import Options
522
523
def load_config_file(config_path):
524
"""Load configuration from JSON file."""
525
with open(config_path, 'r') as f:
526
config = json.load(f)
527
528
# Convert config to command line arguments
529
args = ["nuitka"]
530
531
if config.get("standalone"):
532
args.append("--standalone")
533
534
if config.get("verbose"):
535
args.append("--verbose")
536
537
for plugin in config.get("plugins", []):
538
args.append(f"--plugin-enable={plugin}")
539
540
for package in config.get("include_packages", []):
541
args.append(f"--include-package={package}")
542
543
args.append(config["source_file"])
544
545
sys.argv = args
546
Options.parseArgs()
547
Options.commentArgs()
548
549
# Example config.json:
550
# {
551
# "standalone": true,
552
# "verbose": true,
553
# "plugins": ["numpy", "tk-inter"],
554
# "include_packages": ["requests"],
555
# "source_file": "myapp.py"
556
# }
557
```
558
559
## Error Handling
560
561
### Configuration Errors
562
563
Handle various configuration error scenarios.
564
565
```python
566
from nuitka import Options
567
568
def safe_parse_options():
569
"""Safely parse options with error handling."""
570
try:
571
Options.parseArgs()
572
Options.commentArgs()
573
return True
574
575
except SystemExit as e:
576
if e.code == 0:
577
# Help was displayed
578
return False
579
else:
580
print(f"Argument parsing failed: {e}")
581
return False
582
583
except Exception as e:
584
print(f"Configuration error: {e}")
585
return False
586
587
# Usage with error handling
588
if safe_parse_options():
589
print("Configuration successful")
590
591
# Proceed with compilation
592
if Options.shallMakeExe():
593
print("Ready for executable compilation")
594
else:
595
print("Configuration failed")
596
```
597
598
## Types
599
600
```python { .api }
601
# Option state types
602
OptionValue = str | bool | int | list
603
OptionDict = dict[str, OptionValue]
604
605
# Mode types
606
CompilationMode = str # 'standalone', 'module', 'package'
607
OptimizationLevel = int # 0-3
608
VerbosityLevel = int # 0-2
609
610
# Configuration result types
611
ParseResult = bool
612
ValidationResult = bool
613
```