Run Python scripts from Node.js with efficient inter-process communication through stdio
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
Executes a Python script file and returns collected output messages as a promise.
/**
* Runs a Python script and returns collected messages as a promise
* If the promise is rejected, the error will be of type PythonShellErrorWithLogs
* @param scriptPath - The path to the script to execute
* @param options - The execution options
* @returns Promise resolving to array of output messages
*/
static run(scriptPath: string, options?: Options): Promise<any[]>;Usage Examples:
import { PythonShell } from "python-shell";
// Basic script execution
const results = await PythonShell.run('hello.py');
console.log(results); // ['Hello, World!']
// Script with arguments and options
const results = await PythonShell.run('process_data.py', {
mode: 'json',
pythonPath: '/usr/bin/python3',
scriptPath: './scripts',
args: ['input.csv', 'output.json'],
pythonOptions: ['-u'] // unbuffered output
});
// Error handling with logs
try {
const results = await PythonShell.run('failing_script.py');
} catch (error) {
console.log('Error:', error.message);
console.log('Script output before error:', error.logs);
console.log('Exit code:', error.exitCode);
console.log('Python traceback:', error.traceback);
}Executes a string of Python code and returns collected output messages as a promise.
/**
* Runs Python code string and returns collected messages as a promise
* DO NOT ALLOW UNTRUSTED USER INPUT - security risk of arbitrary code execution
* @param code - The Python code to execute
* @param options - The execution options
* @returns Promise resolving to array of output messages
*/
static runString(code: string, options?: Options): Promise<any[]>;Usage Examples:
import { PythonShell } from "python-shell";
// Simple code execution
const results = await PythonShell.runString('print("Hello"); print("World")');
console.log(results); // ['Hello', 'World']
// Code with calculations
const results = await PythonShell.runString(`
import math
for i in range(3):
print(math.sqrt(i + 1))
`);
console.log(results); // ['1.0', '1.4142135623730951', '1.7320508075688772']
// JSON mode for structured data
const results = await PythonShell.runString(`
import json
data = {'numbers': [1, 2, 3], 'message': 'success'}
print(json.dumps(data))
`, { mode: 'json' });
console.log(results); // [{ numbers: [1, 2, 3], message: 'success' }]
// Using different Python version
const results = await PythonShell.runString('print("Hello from Python")', {
pythonPath: 'python3.9'
});Both methods throw PythonShellErrorWithLogs when the Python process exits with a non-zero code:
class PythonShellErrorWithLogs extends PythonShellError {
logs: any[]; // Output collected before error occurred
traceback: string | Buffer; // Python traceback if available
exitCode?: number; // Process exit code
}The error includes:
Both methods support different data exchange modes:
Example with different modes:
// Text mode (default)
const textResults = await PythonShell.runString('print("line1"); print("line2")');
// Result: ['line1', 'line2']
// JSON mode
const jsonResults = await PythonShell.runString(`
import json
print(json.dumps({"key": "value1"}))
print(json.dumps({"key": "value2"}))
`, { mode: 'json' });
// Result: [{ key: 'value1' }, { key: 'value2' }]Install with Tessl CLI
npx tessl i tessl/npm-python-shell