0
# Script Execution
1
2
Static methods for executing Python scripts and code strings with promise-based results collection. These methods provide a simple, one-time execution pattern ideal for batch processing and result collection.
3
4
## Capabilities
5
6
### Run Python Script
7
8
Executes a Python script file and returns collected output messages as a promise.
9
10
```typescript { .api }
11
/**
12
* Runs a Python script and returns collected messages as a promise
13
* If the promise is rejected, the error will be of type PythonShellErrorWithLogs
14
* @param scriptPath - The path to the script to execute
15
* @param options - The execution options
16
* @returns Promise resolving to array of output messages
17
*/
18
static run(scriptPath: string, options?: Options): Promise<any[]>;
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
import { PythonShell } from "python-shell";
25
26
// Basic script execution
27
const results = await PythonShell.run('hello.py');
28
console.log(results); // ['Hello, World!']
29
30
// Script with arguments and options
31
const results = await PythonShell.run('process_data.py', {
32
mode: 'json',
33
pythonPath: '/usr/bin/python3',
34
scriptPath: './scripts',
35
args: ['input.csv', 'output.json'],
36
pythonOptions: ['-u'] // unbuffered output
37
});
38
39
// Error handling with logs
40
try {
41
const results = await PythonShell.run('failing_script.py');
42
} catch (error) {
43
console.log('Error:', error.message);
44
console.log('Script output before error:', error.logs);
45
console.log('Exit code:', error.exitCode);
46
console.log('Python traceback:', error.traceback);
47
}
48
```
49
50
### Run Python Code String
51
52
Executes a string of Python code and returns collected output messages as a promise.
53
54
```typescript { .api }
55
/**
56
* Runs Python code string and returns collected messages as a promise
57
* DO NOT ALLOW UNTRUSTED USER INPUT - security risk of arbitrary code execution
58
* @param code - The Python code to execute
59
* @param options - The execution options
60
* @returns Promise resolving to array of output messages
61
*/
62
static runString(code: string, options?: Options): Promise<any[]>;
63
```
64
65
**Usage Examples:**
66
67
```typescript
68
import { PythonShell } from "python-shell";
69
70
// Simple code execution
71
const results = await PythonShell.runString('print("Hello"); print("World")');
72
console.log(results); // ['Hello', 'World']
73
74
// Code with calculations
75
const results = await PythonShell.runString(`
76
import math
77
for i in range(3):
78
print(math.sqrt(i + 1))
79
`);
80
console.log(results); // ['1.0', '1.4142135623730951', '1.7320508075688772']
81
82
// JSON mode for structured data
83
const results = await PythonShell.runString(`
84
import json
85
data = {'numbers': [1, 2, 3], 'message': 'success'}
86
print(json.dumps(data))
87
`, { mode: 'json' });
88
console.log(results); // [{ numbers: [1, 2, 3], message: 'success' }]
89
90
// Using different Python version
91
const results = await PythonShell.runString('print("Hello from Python")', {
92
pythonPath: 'python3.9'
93
});
94
```
95
96
## Error Handling
97
98
Both methods throw `PythonShellErrorWithLogs` when the Python process exits with a non-zero code:
99
100
```typescript { .api }
101
class PythonShellErrorWithLogs extends PythonShellError {
102
logs: any[]; // Output collected before error occurred
103
traceback: string | Buffer; // Python traceback if available
104
exitCode?: number; // Process exit code
105
}
106
```
107
108
The error includes:
109
- **logs**: All output messages collected before the error occurred
110
- **traceback**: Full Python traceback when available
111
- **exitCode**: The exit code of the Python process
112
- **message**: The exception message from Python
113
114
## Data Modes
115
116
Both methods support different data exchange modes:
117
118
- **text**: Each line of output becomes a string message (default)
119
- **json**: Each line is parsed as JSON and becomes an object message
120
- **binary**: Raw data mode (not recommended for these methods)
121
122
Example with different modes:
123
124
```typescript
125
// Text mode (default)
126
const textResults = await PythonShell.runString('print("line1"); print("line2")');
127
// Result: ['line1', 'line2']
128
129
// JSON mode
130
const jsonResults = await PythonShell.runString(`
131
import json
132
print(json.dumps({"key": "value1"}))
133
print(json.dumps({"key": "value2"}))
134
`, { mode: 'json' });
135
// Result: [{ key: 'value1' }, { key: 'value2' }]
136
```