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.
- 🚀 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
# Install locally (for use with npx)
npm install @dynamicaaa/pyrunner
# Or install globally for direct access
npm install -g @dynamicaaa/pyrunnerimport 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);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);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);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.
# Install globally for direct access
npm install -g @dynamicaaa/pyrunner
# Or use npx with local installation
npx pyrunner --help# 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# 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.jsonThe 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)
interface PyRunnerOptions {
pythonDir?: string; // Custom Python installation directory
debug?: boolean; // Enable debug logging
enableColors?: boolean; // Enable colored output (default: true)
}Initialize the Python environment. Called automatically when needed.
await pyRunner.init();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
}Execute a Python file.
const result = await pyRunner.runFile('./my-script.py', {
args: ['--verbose'],
realtime: true
});Install Python packages using pip.
interface InstallOptions extends RunOptions {
upgrade?: boolean; // Upgrade packages
user?: boolean; // Install to user directory
}List all installed Python packages.
const packages = await pyRunner.listPackages();
console.log(packages);
// [{name: "requests", version: "2.28.1"}, ...]Get the Python version.
const version = await pyRunner.getVersion();
console.log('Python version:', version);Enable or disable colored output.
pyRunner.setColorEnabled(false); // Disable colors
pyRunner.setColorEnabled(true); // Enable colorsimport { 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();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());
}
});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!'
}
});- 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
- Node.js 14.0.0 or higher
- Internet connection (for initial Python download)
MIT © Dynamicaaa
Contributions are welcome! Please feel free to submit a Pull Request.
See the examples/ directory for more comprehensive examples:
examples/run-code.js- Running Python code stringsexamples/run-file.js- Running Python filesexamples/install-package.js- Installing and using packages
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/pythonColored output not working
// Enable colors explicitly
pyRunner.setColorEnabled(true);
// Or run with inheritStdio
await pyRunner.runCode('print("Hello")', { inheritStdio: true });