Mini Racer
Mini Racer is a minimal, modern embedded V8 JavaScript engine for Python. It allows executing JavaScript code directly within Python applications. As of version 0.14.1, it provides a stable API for evaluating JS, calling functions, and managing execution contexts. The project has a relatively frequent release cadence, with minor updates and bug fixes appearing every few weeks or months.
Warnings
- breaking The import path for `MiniRacer` changed significantly. Direct class import `from py_mini_racer import MiniRacer` is now required.
- breaking JavaScript errors no longer propagate as generic Python exceptions but raise a specific `MiniRacerEvalError`.
- breaking The `v8_args` parameter was removed from the `MiniRacer` constructor.
- breaking The `timeout` parameter was removed from the `MiniRacer` constructor. While it was briefly available in v0.12.x, it was removed from the constructor in v0.13.0.
- gotcha A `MiniRacer` instance is NOT thread-safe. Accessing a single instance from multiple threads concurrently can lead to crashes or undefined behavior.
Install
-
pip install mini-racer
Imports
- MiniRacer
from py_mini_racer import MiniRacer
- MiniRacerEvalError
from py_mini_racer import MiniRacerEvalError
Quickstart
from py_mini_racer import MiniRacer, MiniRacerEvalError
# Initialize a MiniRacer context
mr = MiniRacer()
# Evaluate JavaScript code to define a function
mr.eval("function add(a, b) { return a + b; }")
# Call the JavaScript function with Python arguments
result = mr.call("add", 1, 2)
print(f"Result of add(1, 2): {result}")
# Evaluate a simple expression (e.g., getting V8 version)
js_version = mr.eval("process.versions.v8")
print(f"V8 version: {js_version}")
# Demonstrate error handling
try:
mr.eval("throw new Error('Something went wrong!');")
excep MiniRacerEvalError as e:
print(f"Caught MiniRacerEvalError: {e}")