Skip to content

Run Python code and files from JavaScript with a portable Python environment. PyRunner automatically downloads and manages a Python runtime, making it perfect for embedding Python functionality in Node.js applications.

License

Notifications You must be signed in to change notification settings

Dynamicaaa/pyrunner

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PyRunner

License: MIT

Run Python code and files from JavaScript with a portable Python environment. PyRunner automatically downloads and manages a Python runtime, making it perfect for embedding Python functionality in Node.js applications.

Features

  • 🚀 Zero Configuration - Automatically downloads and sets up Python if not available
  • 🐍 Cross-Platform - Works on Windows, macOS, and Linux
  • 🎨 Colored Output - Supports ANSI colors in terminals
  • 📦 Package Management - Install Python packages with pip
  • 🔄 Real-time Output - Stream Python output in real-time
  • 🛠️ Simple API - Easy to use with minimal setup

Installation

# Install locally (for use with npx)
npm install @dynamicaaa/pyrunner

# Or install globally for direct access
npm install -g @dynamicaaa/pyrunner

Quick Start

Run Python Code

import pyRunner from 'pyrunner';

async function main() {
  // Run Python code directly
  const result = await pyRunner.runCode(`
    print("Hello from Python!")
    name = "World"
    print(f"Hello, {name}!")
    import math
    print(f"Pi is approximately {math.pi:.2f}")
  `);

  console.log('Exit code:', result.exitCode);
  console.log('Output:', result.stdout);
}

main().catch(console.error);

Run Python Files

import pyRunner from 'pyrunner';

async function main() {
  // Run a Python file
  const result = await pyRunner.runFile('./script.py', {
    realtime: true  // Show output in real-time
  });

  console.log('Script finished with exit code:', result.exitCode);
}

main().catch(console.error);

Install Python Packages

import pyRunner from 'pyrunner';

async function main() {
  // Install a Python package
  const result = await pyRunner.installPackage('requests', {
    realtime: true
  });

  if (result.exitCode === 0) {
    // Use the installed package
    const result = await pyRunner.runCode(`
      import requests
      response = requests.get('https://api.github.com/user', params={'access_token': 'your_token'})
      print(f"Status: {response.status_code}")
      print(f"User: {response.json()['login']}")
    `);

    console.log(result.stdout);
  }
}

main().catch(console.error);

Command Line Interface

PyRunner includes a command-line interface that allows you to run Python directly from your terminal. It automatically manages the portable Python environment and passes all arguments through to the Python interpreter.

CLI Installation

# Install globally for direct access
npm install -g @dynamicaaa/pyrunner

# Or use npx with local installation
npx pyrunner --help

CLI Usage

# Start Python REPL
pyrunner

# Execute Python code
pyrunner -c "print('Hello, World!')"

# Run Python file
pyrunner script.py

# Run Python file with arguments
pyrunner script.py arg1 arg2

# Run Python module
pyrunner -m pip install requests

# Run Python module with arguments
pyrunner -m json.tool data.json

# Show Python version
pyrunner --version

# Get help
pyrunner --help

CLI Examples

# Quick Python calculations
pyrunner -c "import math; print(f'Pi: {math.pi:.4f}')"

# Install and use packages
pyrunner -m pip install requests
pyrunner -c "import requests; print(requests.get('https://api.github.com').status_code)"

# Process JSON data
echo '{"name": "test", "value": 42}' | pyrunner -m json.tool

# Run scripts with arguments
pyrunner myscript.py --input data.txt --output result.json

The CLI automatically:

  • Downloads and sets up Python if not available
  • Passes through all arguments to Python
  • Supports colored output in terminals
  • Works cross-platform (Windows, macOS, Linux)

API Reference

PyRunner Class

Constructor Options

interface PyRunnerOptions {
  pythonDir?: string;      // Custom Python installation directory
  debug?: boolean;         // Enable debug logging
  enableColors?: boolean;  // Enable colored output (default: true)
}

Methods

init(): Promise<void>

Initialize the Python environment. Called automatically when needed.

await pyRunner.init();
runCode(code: string, options?: RunOptions): Promise<RunResult>

Execute Python code from a string.

interface RunOptions {
  inheritStdio?: boolean;  // Inherit stdio for colored output
  realtime?: boolean;      // Enable real-time output to console
  cwd?: string;           // Working directory
  env?: object;           // Environment variables
  onStdout?: (data: string) => void;  // Stdout callback
  onStderr?: (data: string) => void;  // Stderr callback
}

interface RunResult {
  stdout: string;    // Standard output
  stderr: string;    // Standard error
  exitCode: number;  // Exit code
}
runFile(filePath: string, options?: RunOptions): Promise<RunResult>

Execute a Python file.

const result = await pyRunner.runFile('./my-script.py', {
  args: ['--verbose'],
  realtime: true
});
installPackage(packages: string | string[], options?: InstallOptions): Promise<RunResult>

Install Python packages using pip.

interface InstallOptions extends RunOptions {
  upgrade?: boolean;  // Upgrade packages
  user?: boolean;     // Install to user directory
}
listPackages(): Promise<Array<{name: string, version: string}>>

List all installed Python packages.

const packages = await pyRunner.listPackages();
console.log(packages);
// [{name: "requests", version: "2.28.1"}, ...]
getVersion(): Promise<string>

Get the Python version.

const version = await pyRunner.getVersion();
console.log('Python version:', version);
setColorEnabled(enabled: boolean): void

Enable or disable colored output.

pyRunner.setColorEnabled(false);  // Disable colors
pyRunner.setColorEnabled(true);   // Enable colors

Advanced Usage

Custom Configuration

import { PyRunner } from 'pyrunner';

const runner = new PyRunner({
  pythonDir: './custom-python',  // Custom installation path
  debug: true,                   // Enable debug logging
  enableColors: false            // Disable colored output
});

await runner.init();

Real-time Output Handling

const result = await pyRunner.runCode(`
  import time
  for i in range(3):
    print(f"Step {i+1}")
    time.sleep(1)
`, {
  realtime: true,
  onStdout: (data) => {
    // Custom stdout handling
    console.log('[PYTHON]:', data.trim());
  },
  onStderr: (data) => {
    // Custom stderr handling
    console.error('[PYTHON ERROR]:', data.trim());
  }
});

Environment Variables

const result = await pyRunner.runCode(`
  import os
  print(f"HOME: {os.environ.get('HOME')}")
  print(f"CUSTOM_VAR: {os.environ.get('CUSTOM_VAR')}")
`, {
  env: {
    CUSTOM_VAR: 'Hello from Node.js!'
  }
});

Platform Support

  • Windows: Uses Python embeddable package from python.org
  • macOS: Uses system Python or creates a virtual environment
  • Linux: Uses system Python or creates a virtual environment

Requirements

  • Node.js 14.0.0 or higher
  • Internet connection (for initial Python download)

License

MIT © Dynamicaaa

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Examples

See the examples/ directory for more comprehensive examples:

Troubleshooting

Common Issues

Python download fails

  • Ensure you have internet connectivity
  • Check firewall settings
  • On corporate networks, you may need to configure proxy settings

Permission errors on Linux/macOS

# Create the python directory manually
mkdir -p ~/.pyrunner/python

Colored output not working

// Enable colors explicitly
pyRunner.setColorEnabled(true);

// Or run with inheritStdio
await pyRunner.runCode('print("Hello")', { inheritStdio: true });

About

Run Python code and files from JavaScript with a portable Python environment. PyRunner automatically downloads and manages a Python runtime, making it perfect for embedding Python functionality in Node.js applications.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published