Run Python scripts from Node.js with efficient inter-process communication through stdio
npx @tessl/cli install tessl/npm-python-shell@5.0.0Python Shell is a Node.js TypeScript library that provides efficient inter-process communication between Node.js and Python through child processes. It offers promise-based APIs, multiple data exchange modes, error handling with Python tracebacks, and both interactive and one-time execution patterns.
npm install python-shellimport { PythonShell } from "python-shell";For CommonJS:
const { PythonShell } = require("python-shell");Additional imports for interfaces and utilities:
import { PythonShell, Options, PythonShellError, NewlineTransformer } from "python-shell";
import { Transform } from "stream"; // For custom splittersimport { PythonShell } from "python-shell";
// Run a Python script and get results
const results = await PythonShell.run('my_script.py', {
mode: 'text',
pythonPath: 'python3',
scriptPath: './scripts',
args: ['arg1', 'arg2']
});
// Execute Python code directly
const output = await PythonShell.runString('print("Hello from Python")');
console.log(output); // ['Hello from Python']
// Interactive communication
const pyshell = new PythonShell('interactive_script.py');
pyshell.send('input data');
pyshell.on('message', (message) => {
console.log('Received:', message);
});
pyshell.end((err, code, signal) => {
if (err) throw err;
console.log('Process finished with code:', code);
});Python Shell is built around several key components:
run, runString) for one-time Python script executionStatic methods for executing Python scripts and code strings with promise-based results collection.
static run(scriptPath: string, options?: Options): Promise<any[]>;
static runString(code: string, options?: Options): Promise<any[]>;Interactive Python shell class for persistent processes with real-time data exchange through events and streams.
class PythonShell extends EventEmitter {
constructor(scriptPath: string, options?: Options, stdoutSplitter: Transform = null, stderrSplitter: Transform = null);
send(message: string | Object): PythonShell;
end(callback: (err: PythonShellError, exitCode: number, exitSignal: string) => any): PythonShell;
kill(signal?: NodeJS.Signals): PythonShell;
}Comprehensive configuration interface for customizing Python execution environment, data handling, and process options.
interface Options extends SpawnOptions {
mode?: 'text' | 'json' | 'binary';
formatter?: string | ((param: string) => any);
parser?: string | ((param: string) => any);
stderrParser?: string | ((param: string) => any);
encoding?: BufferEncoding;
pythonPath?: string;
pythonOptions?: string[];
scriptPath?: string;
args?: string[];
}Utility functions for Python environment management, syntax checking, and stream processing.
static checkSyntax(code: string): Promise<void>;
static checkSyntaxFile(filePath: string): Promise<void>;
static getVersion(pythonPath?: string): Promise<{stdout: string, stderr: string}>;
static getVersionSync(pythonPath?: string): string;
static getPythonPath(): string;static defaultPythonPath: string; // Default Python executable path
static defaultOptions: Options; // Global default options for all instances
static format: { // Built-in formatters
text: (data: any) => string;
json: (data: any) => string;
};
static parse: { // Built-in parsers
text: (data: string) => string;
json: (data: string) => any;
};class PythonShellError extends Error {
traceback: string | Buffer;
exitCode?: number;
}
class PythonShellErrorWithLogs extends PythonShellError {
logs: any[];
}
class NewlineTransformer extends Transform {
_transform(chunk: any, encoding: string, callback: TransformCallback): void;
_flush(done: TransformCallback): void;
}