CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-python-shell

Run Python scripts from Node.js with efficient inter-process communication through stdio

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Python Shell

Python 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.

Package Information

  • Package Name: python-shell
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install python-shell

Core Imports

import { 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 splitters

Basic Usage

import { 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);
});

Architecture

Python Shell is built around several key components:

  • PythonShell Class: Main interactive shell for persistent Python processes with event-driven communication
  • Static Execution Methods: Utility functions (run, runString) for one-time Python script execution
  • Stream Processing: Built-in parsers/formatters for text, JSON, and binary data modes
  • Error Handling: Extended error reporting with Python traceback integration
  • Configuration System: Comprehensive options for Python path, arguments, and execution environment

Capabilities

Script Execution

Static 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[]>;

Script Execution

Interactive Shell

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;
}

Interactive Shell

Configuration Options

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[];
}

Configuration

Utilities

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;

Utilities

Static Properties

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;
};

Core Types

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;
}

docs

configuration.md

index.md

interactive-shell.md

script-execution.md

utilities.md

tile.json