0
# Python Interpreter Initialization
1
2
Complete API for initializing and configuring Python interpreters within Java applications. This includes basic initialization, advanced configuration, pre-initialization setup, and proper cleanup procedures.
3
4
## Capabilities
5
6
### Basic Initialization
7
8
Simple initialization functions for common use cases where default configuration is sufficient.
9
10
```java { .api }
11
/**
12
* Initialize Python interpreter with default settings
13
*/
14
public static native void Py_Initialize();
15
16
/**
17
* Initialize Python interpreter with signal handling control
18
* @param initsigs - If non-zero, initialize signal handling
19
*/
20
public static native void Py_InitializeEx(int initsigs);
21
22
/**
23
* Finalize Python interpreter and free all memory
24
*/
25
public static native void Py_Finalize();
26
27
/**
28
* Finalize Python interpreter with error code return
29
* @return 0 on success, -1 on error
30
*/
31
public static native int Py_FinalizeEx();
32
```
33
34
**Usage Example:**
35
36
```java
37
import static org.bytedeco.cpython.global.python.*;
38
39
// Basic initialization
40
Py_Initialize();
41
42
// Your Python operations here
43
PyRun_SimpleString("print('Python is running!')");
44
45
// Always finalize when done
46
Py_Finalize();
47
```
48
49
### Helper Initialization (Convenience Methods)
50
51
Simplified initialization methods provided by the helper library for common scenarios.
52
53
```java { .api }
54
/**
55
* Initialize Python with additional library paths
56
* @param path - Additional paths to add to Python sys.path
57
* @return true if initialization successful, false otherwise
58
* @throws IOException if path operations fail
59
*/
60
public static boolean Py_Initialize(File... path) throws IOException;
61
62
/**
63
* Initialize Python with additional library paths as strings
64
* @param path - Additional paths to add to Python sys.path
65
* @return true if initialization successful, false otherwise
66
* @throws IOException if path operations fail
67
*/
68
public static boolean Py_Initialize(String... path) throws IOException;
69
```
70
71
**Usage Example:**
72
73
```java
74
import org.bytedeco.cpython.helper.python;
75
76
// Initialize with custom Python library paths
77
boolean success = python.Py_Initialize(
78
"/usr/local/lib/python3.13",
79
"/opt/myapp/python-modules"
80
);
81
82
if (success) {
83
// Python ready to use
84
PyRun_SimpleString("import sys; print(sys.path)");
85
}
86
```
87
88
### Configuration-Based Initialization
89
90
Advanced initialization using configuration structures for fine-grained control over the Python interpreter.
91
92
```java { .api }
93
/**
94
* Initialize Python from configuration object
95
* @param config - Configuration structure
96
* @return Status indicating success or failure
97
*/
98
public static native PyStatus Py_InitializeFromConfig(PyConfig config);
99
100
/**
101
* Initialize configuration with Python defaults
102
* @param config - Configuration structure to initialize
103
*/
104
public static native void PyConfig_InitPythonConfig(PyConfig config);
105
106
/**
107
* Initialize configuration in isolated mode
108
* @param config - Configuration structure to initialize
109
*/
110
public static native void PyConfig_InitIsolatedConfig(PyConfig config);
111
112
/**
113
* Clear and deallocate configuration structure
114
* @param config - Configuration to clear
115
*/
116
public static native void PyConfig_Clear(PyConfig config);
117
118
/**
119
* Set string value in configuration
120
* @param config - Configuration structure
121
* @param configField - Pointer to the field to set
122
* @param value - String value to set
123
* @return Status indicating success or failure
124
*/
125
public static native PyStatus PyConfig_SetString(PyConfig config, PointerPointer configField, Pointer value);
126
```
127
128
**Usage Example:**
129
130
```java
131
import static org.bytedeco.cpython.global.python.*;
132
133
// Create and configure Python
134
PyConfig config = new PyConfig();
135
PyConfig_InitPythonConfig(config);
136
137
// Initialize with configuration
138
PyStatus status = Py_InitializeFromConfig(config);
139
140
if (!PyStatus_IsError(status)) {
141
// Python initialized successfully
142
PyRun_SimpleString("print('Configured Python running!')");
143
} else {
144
System.err.println("Python initialization failed");
145
}
146
147
// Clean up configuration
148
PyConfig_Clear(config);
149
```
150
151
### Pre-Initialization Configuration
152
153
Control Python interpreter behavior before main initialization occurs.
154
155
```java { .api }
156
/**
157
* Pre-initialize Python interpreter
158
* @param src_config - Pre-initialization configuration
159
* @return Status indicating success or failure
160
*/
161
public static native PyStatus Py_PreInitialize(PyPreConfig src_config);
162
163
/**
164
* Pre-initialize from arguments
165
* @param src_config - Pre-initialization configuration
166
* @param argc - Argument count
167
* @param argv - Argument vector
168
* @return Status indicating success or failure
169
*/
170
public static native PyStatus Py_PreInitializeFromArgs(PyPreConfig src_config, int argc, PointerPointer argv);
171
172
/**
173
* Initialize pre-configuration with defaults
174
* @param config - Pre-configuration structure
175
*/
176
public static native void PyPreConfig_InitPythonConfig(PyPreConfig config);
177
178
/**
179
* Initialize pre-configuration in isolated mode
180
* @param config - Pre-configuration structure
181
*/
182
public static native void PyPreConfig_InitIsolatedConfig(PyPreConfig config);
183
```
184
185
### Status Management
186
187
Functions for checking and handling initialization status results.
188
189
```java { .api }
190
/**
191
* Check if status indicates an error
192
* @param status - Status to check
193
* @return Non-zero if error occurred
194
*/
195
public static native int PyStatus_IsError(PyStatus status);
196
197
/**
198
* Check if status indicates exit was requested
199
* @param status - Status to check
200
* @return Non-zero if exit requested
201
*/
202
public static native int PyStatus_IsExit(PyStatus status);
203
204
/**
205
* Check if status indicates an exception
206
* @param status - Status to check
207
* @return Non-zero if exception occurred
208
*/
209
public static native int PyStatus_Exception(PyStatus status);
210
```
211
212
### Interpreter State Management
213
214
Functions for managing multiple Python interpreters and sub-interpreters.
215
216
```java { .api }
217
/**
218
* Create new interpreter configuration
219
* @param config - Configuration structure to initialize
220
*/
221
public static native void PyInterpreterConfig_InitLegacyConfig(PyInterpreterConfig config);
222
223
/**
224
* Get current interpreter state
225
* @return Current interpreter state
226
*/
227
public static native PyInterpreterState PyInterpreterState_Get();
228
229
/**
230
* Create new sub-interpreter
231
* @param tstate_p - Pointer to receive new thread state
232
* @param config - Interpreter configuration
233
* @return Status indicating success or failure
234
*/
235
public static native PyStatus Py_NewInterpreterFromConfig(PointerPointer tstate_p, PyInterpreterConfig config);
236
```
237
238
## Key Configuration Types
239
240
```java { .api }
241
/**
242
* Main Python configuration structure
243
*/
244
class PyConfig extends Pointer {
245
// Contains all configuration options for Python initialization
246
// Fields accessed through PyConfig_SetString and similar functions
247
}
248
249
/**
250
* Pre-initialization configuration
251
*/
252
class PyPreConfig extends Pointer {
253
// Configuration applied before main Python initialization
254
// Controls allocator, locale, and other low-level settings
255
}
256
257
/**
258
* Status return structure for initialization operations
259
*/
260
class PyStatus extends Pointer {
261
// Contains result of initialization operations
262
// Check with PyStatus_IsError, PyStatus_IsExit functions
263
}
264
265
/**
266
* Interpreter-specific configuration
267
*/
268
class PyInterpreterConfig extends Pointer {
269
// Configuration for individual interpreter instances
270
// Used with sub-interpreter creation
271
}
272
273
/**
274
* Python interpreter state
275
*/
276
class PyInterpreterState extends Pointer {
277
// Represents an individual Python interpreter instance
278
}
279
```
280
281
## Advanced Usage Patterns
282
283
### Custom Configuration Setup
284
285
```java
286
import static org.bytedeco.cpython.global.python.*;
287
288
// Create isolated configuration
289
PyConfig config = new PyConfig();
290
PyConfig_InitIsolatedConfig(config);
291
292
// Set custom program name
293
// Note: String handling requires proper wide character conversion
294
// This is typically done through helper methods
295
296
PyStatus status = Py_InitializeFromConfig(config);
297
298
if (!PyStatus_IsError(status)) {
299
// Python running in isolated mode
300
// No access to system Python installation
301
PyRun_SimpleString("import sys; print('Isolated Python:', sys.executable)");
302
303
Py_Finalize();
304
} else {
305
System.err.println("Isolated initialization failed");
306
}
307
308
PyConfig_Clear(config);
309
```
310
311
### Multiple Interpreter Management
312
313
```java
314
import static org.bytedeco.cpython.global.python.*;
315
316
// Initialize main interpreter
317
Py_Initialize();
318
319
// Create sub-interpreter configuration
320
PyInterpreterConfig config = new PyInterpreterConfig();
321
PyInterpreterConfig_InitLegacyConfig(config);
322
323
// Create sub-interpreter
324
PointerPointer tstate_p = new PointerPointer(1);
325
PyStatus status = Py_NewInterpreterFromConfig(tstate_p, config);
326
327
if (!PyStatus_IsError(status)) {
328
PyThreadState subInterpreter = new PyThreadState(tstate_p.get());
329
330
// Switch to sub-interpreter
331
PyThreadState oldState = PyThreadState_Swap(subInterpreter);
332
333
// Run code in sub-interpreter
334
PyRun_SimpleString("print('Running in sub-interpreter')");
335
336
// Switch back to main interpreter
337
PyThreadState_Swap(oldState);
338
339
// Clean up sub-interpreter
340
PyThreadState_Clear(subInterpreter);
341
PyThreadState_Delete(subInterpreter);
342
}
343
344
Py_Finalize();
345
```
346
347
## Error Handling
348
349
Always check initialization status and handle errors appropriately:
350
351
```java
352
PyStatus status = Py_InitializeFromConfig(config);
353
354
if (PyStatus_IsError(status)) {
355
System.err.println("Python initialization failed");
356
// Handle initialization error
357
return;
358
}
359
360
if (PyStatus_IsExit(status)) {
361
System.out.println("Python requested exit during initialization");
362
// Handle exit request
363
return;
364
}
365
366
// Initialization successful, proceed with Python operations
367
```
368
369
## Important Notes
370
371
### Thread Safety
372
373
Python initialization is not thread-safe. Ensure initialization occurs from a single thread before any other threads attempt to use Python APIs.
374
375
### Memory Management
376
377
Configuration structures must be properly cleaned up with `PyConfig_Clear()` to prevent memory leaks.
378
379
### Platform Considerations
380
381
The helper initialization methods handle platform-specific differences in Python installation paths and executable names automatically.