0
# Configuration
1
2
Jython provides extensive configuration options to customize runtime behavior, system state, module loading, and performance characteristics.
3
4
## System State Configuration
5
6
### PySystemState
7
8
Manages the global Python system state, equivalent to Python's `sys` module.
9
10
```java { .api }
11
public class PySystemState extends PyObject {
12
// Initialization
13
public static void initialize();
14
public static void initialize(Properties preProperties, Properties postProperties);
15
public static void initialize(Properties preProperties, Properties postProperties, String[] argv);
16
public static PySystemState getDefault();
17
18
// System attributes
19
public PyList path; // Module search path (sys.path)
20
public PyList argv; // Command line arguments (sys.argv)
21
public PyDictionary modules; // Loaded modules cache (sys.modules)
22
public PyObject stdin; // Standard input stream
23
public PyObject stdout; // Standard output stream
24
public PyObject stderr; // Standard error stream
25
public PyString version; // Python version string
26
public PyTuple version_info; // Version information tuple
27
public PyString platform; // Platform identifier
28
public PyString prefix; // Installation prefix
29
public PyString exec_prefix; // Executable prefix
30
31
// Path management
32
public static void add_package(String n);
33
public static void add_extdir(File file);
34
public static void add_classdir(File file);
35
36
// Module management
37
public PyObject getBuiltins();
38
public void setBuiltins(PyObject builtins);
39
40
// Cleanup
41
public void close();
42
}
43
```
44
45
## Runtime Options
46
47
### Options Class
48
49
Global configuration options that affect Jython runtime behavior.
50
51
```java { .api }
52
public class Options {
53
// Exception handling
54
public static boolean showJavaExceptions = false;
55
public static boolean includeJavaStackInExceptions = true;
56
public static boolean showPythonProxyExceptions = false;
57
58
// Security and access control
59
public static boolean respectJavaAccessibility = true;
60
61
// Module importing and site packages
62
public static boolean importSite = true;
63
public static boolean no_site = false;
64
65
// Interactive mode and inspection
66
public static boolean interactive = false;
67
public static boolean inspect = false;
68
69
// Case sensitivity and imports
70
public static boolean caseok = false;
71
72
// Verbosity and debugging
73
public static int verbose = 0;
74
public static String proxyDebugDirectory;
75
76
// Python 3 compatibility and warnings
77
public static boolean Qnew = false;
78
public static boolean py3k_warning = false;
79
public static int bytes_warning = 0;
80
public static int division_warning = 0;
81
82
// I/O and environment
83
public static boolean unbuffered = false;
84
public static boolean ignore_environment = false;
85
public static boolean no_user_site = false;
86
87
// Compilation and optimization
88
public static boolean dont_write_bytecode = false;
89
public static int optimize = 0;
90
91
// Regular expression caching
92
public static String sreCacheSpec;
93
}
94
```
95
96
## Configuration Examples
97
98
### Basic System Initialization
99
100
```java
101
import org.python.core.*;
102
import org.python.util.PythonInterpreter;
103
import java.util.Properties;
104
105
public class JythonConfig {
106
public static void main(String[] args) {
107
// Configure system properties before initialization
108
Properties preProps = new Properties();
109
preProps.setProperty("python.home", "/path/to/jython");
110
preProps.setProperty("python.executable", "/path/to/jython/bin/jython");
111
112
Properties postProps = new Properties();
113
postProps.setProperty("python.path", "/path/to/modules:/another/path");
114
115
// Initialize with custom properties and arguments
116
String[] jythonArgs = {"--verbose", "script.py"};
117
PythonInterpreter.initialize(preProps, postProps, jythonArgs);
118
119
// Now create interpreter with configured system
120
PythonInterpreter interp = new PythonInterpreter();
121
122
// Use interpreter...
123
interp.close();
124
}
125
}
126
```
127
128
### Runtime Options Configuration
129
130
```java
131
// Configure before creating any interpreters
132
Options.showJavaExceptions = true; // Show Java stack traces
133
Options.includeJavaStackInExceptions = false; // Don't include Java traces in Python exceptions
134
Options.verbose = 2; // High verbosity
135
Options.debug = true; // Enable debug mode
136
Options.respectJavaAccessibility = false; // Allow access to private Java members
137
138
PythonInterpreter interp = new PythonInterpreter();
139
140
// These options are now in effect
141
interp.exec("import sys; print('Verbose level:', sys.flags.verbose)");
142
143
interp.close();
144
```
145
146
### Path Configuration
147
148
```java
149
PySystemState sys = PySystemState.getDefault();
150
151
// Add directories to Python path
152
PyString customPath = Py.newString("/custom/python/modules");
153
sys.path.append(customPath);
154
155
// Add Java packages to be accessible from Python
156
PySystemState.add_package("com.mycompany.mypackage");
157
158
// Add JAR files to classpath
159
PySystemState.add_classdir(new File("/path/to/my-library.jar"));
160
161
// Print current path
162
PythonInterpreter interp = new PythonInterpreter();
163
interp.exec("""
164
import sys
165
print("Python path:")
166
for p in sys.path:
167
print(" ", p)
168
""");
169
interp.close();
170
```
171
172
## Standard I/O Configuration
173
174
### Redirecting I/O Streams
175
176
```java
177
import java.io.*;
178
179
PythonInterpreter interp = new PythonInterpreter();
180
181
// Redirect stdout to a string buffer
182
StringWriter output = new StringWriter();
183
interp.setOut(output);
184
185
// Redirect stderr to a file
186
FileWriter errorLog = new FileWriter("errors.log");
187
interp.setErr(errorLog);
188
189
// Redirect stdin from a string
190
StringReader input = new StringReader("Alice\n25\n");
191
interp.setIn(input);
192
193
// Execute Python code that uses I/O
194
interp.exec("""
195
name = input("Enter name: ")
196
age = int(input("Enter age: "))
197
print(f"Hello, {name}! You are {age} years old.")
198
199
import sys
200
print("This goes to stderr", file=sys.stderr)
201
""");
202
203
// Get captured output
204
String capturedOutput = output.toString();
205
System.out.println("Captured: " + capturedOutput);
206
207
// Close resources
208
errorLog.close();
209
interp.close();
210
```
211
212
### Using PyObject Streams
213
214
```java
215
// Create custom Python stream objects
216
PyObject customOut = new PyFile(new FileOutputStream("custom.out"));
217
PyObject customErr = new PyFile(new FileOutputStream("custom.err"));
218
219
interp.setOut(customOut);
220
interp.setErr(customErr);
221
222
interp.exec("""
223
print("This goes to custom.out")
224
import sys
225
print("This goes to custom.err", file=sys.stderr)
226
""");
227
228
interp.close();
229
```
230
231
## Module and Import Configuration
232
233
### Custom Module Locations
234
235
```java
236
// Add custom module directories before initialization
237
Properties props = new Properties();
238
props.setProperty("python.path",
239
"/custom/modules:/shared/python:/project/src");
240
241
PythonInterpreter.initialize(System.getProperties(), props, new String[0]);
242
243
PythonInterpreter interp = new PythonInterpreter();
244
245
// Now can import from custom locations
246
interp.exec("""
247
# These modules are found in custom paths
248
import my_custom_module
249
from shared_utils import helper_function
250
""");
251
252
interp.close();
253
```
254
255
### Site Packages Configuration
256
257
```java
258
// Disable automatic site package loading
259
Options.importSite = false;
260
Options.no_site = true;
261
262
PythonInterpreter interp = new PythonInterpreter();
263
264
// Manually control what gets imported
265
interp.exec("""
266
# Site packages are not automatically loaded
267
# Need to explicitly add paths if needed
268
import sys
269
sys.path.append('/explicit/path/to/packages')
270
""");
271
272
interp.close();
273
```
274
275
## Security Configuration
276
277
### Java Access Control
278
279
```java
280
// Restrict Java access from Python
281
Options.respectJavaAccessibility = true; // Respect Java private/protected
282
283
PythonInterpreter interp = new PythonInterpreter();
284
285
// This configuration affects what Java members are accessible
286
interp.exec("""
287
from java.lang import String
288
s = String("test")
289
290
# This will work - public method
291
print(s.length())
292
293
# This might fail depending on respectJavaAccessibility setting
294
# if trying to access private fields
295
""");
296
297
interp.close();
298
```
299
300
### Proxy Exception Handling
301
302
```java
303
// Control how proxy exceptions are shown
304
Options.showPythonProxyExceptions = true;
305
306
PythonInterpreter interp = new PythonInterpreter();
307
308
// Define Python class that implements Java interface
309
interp.exec("""
310
class PythonRunnable:
311
def run(self):
312
raise ValueError("Python error in Java interface")
313
314
runnable = PythonRunnable()
315
""");
316
317
// Get the Python object as Java interface
318
Runnable runnable = (Runnable) interp.get("runnable").__tojava__(Runnable.class);
319
320
try {
321
runnable.run(); // This will show Python exception details
322
} catch (Exception e) {
323
System.out.println("Caught: " + e.getMessage());
324
}
325
326
interp.close();
327
```
328
329
## Performance Configuration
330
331
### Optimization Settings
332
333
```java
334
// Enable optimizations before initialization
335
Options.optimize = true; // Enable optimization
336
Options.dont_write_bytecode = true; // Don't write .pyc files
337
338
PythonInterpreter interp = new PythonInterpreter();
339
340
// Check optimization level
341
interp.exec("""
342
import sys
343
print("Optimization level:", sys.flags.optimize)
344
print("Don't write bytecode:", sys.dont_write_bytecode)
345
""");
346
347
interp.close();
348
```
349
350
### Bytecode Caching
351
352
```java
353
// Configure bytecode caching
354
Options.python_cachedir_skip = ".*test.*"; // Skip caching for test files
355
356
// Set custom cache directory via system property
357
System.setProperty("python.cachedir", "/tmp/jython_cache");
358
359
PythonInterpreter interp = new PythonInterpreter();
360
361
interp.exec("""
362
import sys
363
print("Cache directory:", getattr(sys, 'cachedir', 'default'))
364
""");
365
366
interp.close();
367
```
368
369
## Debug and Verbose Configuration
370
371
### Verbose Output Control
372
373
```java
374
// Set different verbosity levels
375
Options.verbose = 3; // Maximum verbosity
376
377
PythonInterpreter interp = new PythonInterpreter();
378
379
// Verbose output will show:
380
// - Module import information
381
// - Compilation details
382
// - Runtime debugging info
383
384
interp.exec("import json"); // Will show verbose import information
385
386
interp.close();
387
```
388
389
### Debug Mode
390
391
```java
392
Options.debug = true;
393
394
PythonInterpreter interp = new PythonInterpreter();
395
396
interp.exec("""
397
import sys
398
print("Debug mode:", sys.flags.debug)
399
400
# Debug mode affects various runtime behaviors
401
# like exception handling and optimization
402
""");
403
404
interp.close();
405
```
406
407
## Advanced Configuration Patterns
408
409
### Environment-Specific Configuration
410
411
```java
412
public class JythonConfigManager {
413
private static final boolean IS_DEVELOPMENT =
414
"development".equals(System.getProperty("environment"));
415
416
public static void configureForEnvironment() {
417
if (IS_DEVELOPMENT) {
418
// Development settings
419
Options.showJavaExceptions = true;
420
Options.verbose = 2;
421
Options.debug = true;
422
Options.dont_write_bytecode = true;
423
} else {
424
// Production settings
425
Options.showJavaExceptions = false;
426
Options.verbose = 0;
427
Options.debug = false;
428
Options.optimize = true;
429
}
430
}
431
432
public static PythonInterpreter createConfiguredInterpreter() {
433
configureForEnvironment();
434
435
Properties props = new Properties();
436
if (IS_DEVELOPMENT) {
437
props.setProperty("python.path", "src:test:lib");
438
} else {
439
props.setProperty("python.path", "lib");
440
}
441
442
PythonInterpreter.initialize(System.getProperties(), props, new String[0]);
443
return new PythonInterpreter();
444
}
445
}
446
```
447
448
### Configuration from Properties File
449
450
```java
451
public class PropertyBasedConfig {
452
public static void configure(String propertiesFile) throws IOException {
453
Properties config = new Properties();
454
config.load(new FileInputStream(propertiesFile));
455
456
// Map properties to Options
457
Options.showJavaExceptions = Boolean.parseBoolean(
458
config.getProperty("jython.showJavaExceptions", "false"));
459
Options.verbose = Integer.parseInt(
460
config.getProperty("jython.verbose", "0"));
461
Options.debug = Boolean.parseBoolean(
462
config.getProperty("jython.debug", "false"));
463
464
// System properties for initialization
465
Properties sysProps = new Properties();
466
sysProps.setProperty("python.home",
467
config.getProperty("python.home", ""));
468
sysProps.setProperty("python.path",
469
config.getProperty("python.path", ""));
470
471
PythonInterpreter.initialize(System.getProperties(), sysProps, new String[0]);
472
}
473
}
474
475
// Usage:
476
// PropertyBasedConfig.configure("jython.properties");
477
```
478
479
## Configuration Validation
480
481
### Runtime Configuration Check
482
483
```java
484
public class ConfigValidator {
485
public static void validateConfiguration() {
486
PythonInterpreter interp = new PythonInterpreter();
487
488
// Check system state
489
PySystemState sys = interp.getSystemState();
490
491
System.out.println("=== Jython Configuration ===");
492
System.out.println("Python version: " + sys.version);
493
System.out.println("Platform: " + sys.platform);
494
System.out.println("Python home: " + System.getProperty("python.home", "not set"));
495
496
// Check path configuration
497
System.out.println("\nPython path:");
498
for (int i = 0; i < sys.path.__len__(); i++) {
499
System.out.println(" " + sys.path.__getitem__(i));
500
}
501
502
// Check options
503
System.out.println("\nRuntime options:");
504
System.out.println(" Show Java exceptions: " + Options.showJavaExceptions);
505
System.out.println(" Verbose level: " + Options.verbose);
506
System.out.println(" Debug mode: " + Options.debug);
507
System.out.println(" Respect Java accessibility: " + Options.respectJavaAccessibility);
508
509
interp.close();
510
}
511
}
512
```
513
514
## Thread-Local Configuration
515
516
### Per-Thread System State
517
518
```java
519
public class ThreadLocalJython {
520
private static final ThreadLocal<PythonInterpreter> THREAD_INTERPRETER =
521
ThreadLocal.withInitial(() -> {
522
// Each thread gets its own interpreter with custom config
523
Properties props = new Properties();
524
props.setProperty("python.path", "thread-local-modules");
525
526
return PythonInterpreter.threadLocalStateInterpreter(
527
Py.newStringMap() // Custom local namespace
528
);
529
});
530
531
public static PythonInterpreter getInterpreter() {
532
return THREAD_INTERPRETER.get();
533
}
534
535
public static void cleanup() {
536
PythonInterpreter interp = THREAD_INTERPRETER.get();
537
if (interp != null) {
538
interp.close();
539
THREAD_INTERPRETER.remove();
540
}
541
}
542
}
543
544
// Usage in multi-threaded environment:
545
// PythonInterpreter interp = ThreadLocalJython.getInterpreter();
546
// interp.exec("print('Thread-specific Python execution')");
547
// ThreadLocalJython.cleanup(); // When thread is done
548
```