0
# Configuration
1
2
Comprehensive configuration interface for customizing Python execution environment, data handling, and process options. The Options interface extends Node.js SpawnOptions to provide Python-specific configuration.
3
4
## Capabilities
5
6
### Options Interface
7
8
Main configuration interface for PythonShell execution options.
9
10
```typescript { .api }
11
/**
12
* Configuration options for PythonShell
13
* Extends Node.js SpawnOptions for child process configuration
14
*/
15
interface Options extends SpawnOptions {
16
/** Data exchange mode for stdin/stdout communication */
17
mode?: 'text' | 'json' | 'binary';
18
/** Custom message formatter function or built-in formatter name */
19
formatter?: string | ((param: string) => any);
20
/** Custom data parser function or built-in parser name */
21
parser?: string | ((param: string) => any);
22
/** Custom stderr parser function or built-in parser name */
23
stderrParser?: string | ((param: string) => any);
24
/** Text encoding for streams */
25
encoding?: BufferEncoding;
26
/** Path to Python executable */
27
pythonPath?: string;
28
/** Command line options for Python */
29
pythonOptions?: string[];
30
/** Override for script directory path */
31
scriptPath?: string;
32
/** Arguments to pass to Python script */
33
args?: string[];
34
}
35
```
36
37
### Data Exchange Modes
38
39
Control how data flows between Node.js and Python processes.
40
41
**Text Mode (default):**
42
```typescript
43
const options: Options = {
44
mode: 'text' // Each line becomes a string message
45
};
46
47
// Python output: print("Hello\nWorld")
48
// Node.js receives: ['Hello', 'World']
49
```
50
51
**JSON Mode:**
52
```typescript
53
const options: Options = {
54
mode: 'json' // Each line parsed as JSON
55
};
56
57
// Python output: print(json.dumps({"key": "value"}))
58
// Node.js receives: [{ key: 'value' }]
59
```
60
61
**Binary Mode:**
62
```typescript
63
const options: Options = {
64
mode: 'binary' // Raw data, no parsing, no message events
65
};
66
// Use for binary data transfer, direct stream access
67
```
68
69
### Custom Formatters and Parsers
70
71
Define custom data processing functions or use built-in ones.
72
73
```typescript { .api }
74
// Built-in formatters
75
static format = {
76
text: (data: any) => string; // Converts to string
77
json: (data: any) => string; // JSON.stringify()
78
};
79
80
// Built-in parsers
81
static parse = {
82
text: (data: string) => string; // Returns as-is
83
json: (data: string) => any; // JSON.parse()
84
};
85
```
86
87
**Usage Examples:**
88
89
```typescript
90
import { PythonShell } from "python-shell";
91
92
// Using built-in formatters/parsers by name
93
const options: Options = {
94
formatter: 'json', // Use built-in JSON formatter
95
parser: 'text', // Use built-in text parser
96
stderrParser: 'text' // stderr always uses text parsing
97
};
98
99
// Custom formatter function
100
const options: Options = {
101
formatter: (data) => {
102
if (typeof data === 'object') {
103
return JSON.stringify(data) + '\n';
104
}
105
return String(data) + '\n';
106
}
107
};
108
109
// Custom parser function
110
const options: Options = {
111
parser: (line) => {
112
// Parse CSV-like format
113
return line.split(',').map(s => s.trim());
114
}
115
};
116
117
// Custom stderr parser
118
const options: Options = {
119
stderrParser: (line) => {
120
// Parse log levels from stderr
121
const match = line.match(/\[(DEBUG|INFO|WARN|ERROR)\] (.+)/);
122
return match ? { level: match[1], message: match[2] } : line;
123
}
124
};
125
```
126
127
### Python Environment Configuration
128
129
Configure Python executable and execution environment.
130
131
**Python Path:**
132
```typescript
133
const options: Options = {
134
pythonPath: '/usr/bin/python3.9', // Specific Python version
135
// or
136
pythonPath: 'python', // Use system default
137
// or
138
pythonPath: './venv/bin/python' // Virtual environment
139
};
140
```
141
142
**Python Options:**
143
```typescript
144
const options: Options = {
145
pythonOptions: [
146
'-u', // Unbuffered stdout/stderr
147
'-O', // Optimize bytecode
148
'-W', 'ignore', // Ignore warnings
149
'-c' // Execute command (when using runString)
150
]
151
};
152
```
153
154
**Script Path:**
155
```typescript
156
const options: Options = {
157
scriptPath: './python_scripts', // Base directory for scripts
158
// Script path combines with scriptPath:
159
// new PythonShell('script.py', { scriptPath: './scripts' })
160
// Executes: './scripts/script.py'
161
};
162
```
163
164
**Script Arguments:**
165
```typescript
166
const options: Options = {
167
args: [
168
'input.txt', // Positional arguments
169
'--verbose', // Flags
170
'--output=result.json' // Key-value arguments
171
]
172
};
173
174
// Python script receives: sys.argv[1:] = ['input.txt', '--verbose', '--output=result.json']
175
```
176
177
### Stream Configuration
178
179
Configure text encoding and stream handling.
180
181
```typescript
182
const options: Options = {
183
encoding: 'utf8', // Default encoding
184
// or
185
encoding: 'ascii', // ASCII encoding
186
// or
187
encoding: 'base64' // Base64 encoding
188
};
189
```
190
191
### Node.js SpawnOptions
192
193
All Node.js child_process.spawn options are available:
194
195
```typescript
196
const options: Options = {
197
// Working directory for Python process
198
cwd: './python_workspace',
199
200
// Environment variables
201
env: {
202
...process.env,
203
PYTHONPATH: './my_modules',
204
DEBUG: '1'
205
},
206
207
// Stdio configuration (advanced)
208
stdio: ['pipe', 'pipe', 'pipe'],
209
210
// Detached process
211
detached: false,
212
213
// Shell execution
214
shell: false,
215
216
// User/group (Unix only)
217
uid: 1000,
218
gid: 1000,
219
220
// Timeout (not recommended, use kill() instead)
221
timeout: 30000
222
};
223
```
224
225
### Default Options
226
227
Set global defaults for all PythonShell instances:
228
229
```typescript { .api }
230
static defaultOptions: Options;
231
```
232
233
**Usage Examples:**
234
235
```typescript
236
import { PythonShell } from "python-shell";
237
238
// Set global defaults
239
PythonShell.defaultOptions = {
240
mode: 'text',
241
pythonPath: '/usr/bin/python3',
242
scriptPath: './python_scripts',
243
pythonOptions: ['-u'],
244
encoding: 'utf8'
245
};
246
247
// All instances inherit these defaults
248
const shell1 = new PythonShell('script1.py'); // Uses defaults
249
const shell2 = new PythonShell('script2.py', {
250
mode: 'json' // Override just the mode
251
});
252
253
// Reset defaults
254
PythonShell.defaultOptions = {};
255
```
256
257
### Complete Configuration Example
258
259
```typescript
260
import { PythonShell, Options } from "python-shell";
261
262
const comprehensiveOptions: Options = {
263
// Data handling
264
mode: 'json',
265
formatter: 'json',
266
parser: 'json',
267
stderrParser: 'text',
268
encoding: 'utf8',
269
270
// Python environment
271
pythonPath: './venv/bin/python',
272
pythonOptions: ['-u', '-O'],
273
scriptPath: './src/python',
274
args: ['--config', 'production.json', '--verbose'],
275
276
// Node.js process options
277
cwd: './workspace',
278
env: {
279
...process.env,
280
PYTHONPATH: './modules',
281
LOG_LEVEL: 'DEBUG'
282
},
283
284
// Advanced stdio
285
stdio: ['pipe', 'pipe', 'pipe']
286
};
287
288
const pyshell = new PythonShell('data_processor.py', comprehensiveOptions);
289
290
// Process will execute:
291
// ./venv/bin/python -u -O ./src/python/data_processor.py --config production.json --verbose
292
// In working directory: ./workspace
293
// With PYTHONPATH=./modules and LOG_LEVEL=DEBUG environment variables
294
```