Run JavaScript code from Python with automatic runtime selection
npx @tessl/cli install tessl/pypi-pyexecjs@1.5.0JavaScript execution bridge for Python applications.
PyExecJS enables execution of JavaScript code from Python applications by automatically selecting the best available JavaScript runtime environment. It provides cross-platform compatibility without requiring manual JavaScript environment setup, supporting multiple JavaScript engines including PyV8, Node.js, PhantomJS, Nashorn, Apple JavaScriptCore, Microsoft Windows Script Host, SlimerJS, and Mozilla SpiderMonkey.
pip install PyExecJSimport execjs
# For runtime classes and exceptions (based on __all__ exports)
from execjs import ExternalRuntime
from execjs import Error, RuntimeError, ProgramError, RuntimeUnavailableError
# For runtime name constants (must import directly from submodule)
import execjs.runtime_names as runtime_namesSimple JavaScript evaluation from Python:
import execjs
# Evaluate JavaScript expression
result = execjs.eval("2 + 2")
print(result) # 4
# Execute JavaScript code with output
output = execjs.exec_("console.log('Hello from JavaScript')")
print(output) # "Hello from JavaScript\n"
# Compile and reuse JavaScript context
ctx = execjs.compile("var add = function(a, b) { return a + b; }")
result = ctx.call("add", 3, 4)
print(result) # 7PyExecJS operates through three main layers:
eval, exec_, compile)Core functionality for evaluating and executing JavaScript code from Python.
def eval(source, cwd=None):
"""
Evaluate JavaScript source code and return the result.
Args:
source (str): JavaScript source code to evaluate
cwd (str, optional): Working directory for execution
Returns:
any: Result of JavaScript evaluation
"""
def exec_(source, cwd=None):
"""
Execute JavaScript source code and return stdout output.
Args:
source (str): JavaScript source code to execute
cwd (str, optional): Working directory for execution
Returns:
str: Standard output from JavaScript execution
"""
def compile(source, cwd=None):
"""
Compile JavaScript source into a reusable context object.
Args:
source (str): JavaScript source code to compile
cwd (str, optional): Working directory for compilation
Returns:
Context object: Compiled JavaScript execution context
"""Manage JavaScript runtime environments and automatic runtime selection.
def get(name=None):
"""
Get a JavaScript runtime by name or automatically select one.
Args:
name (str, optional): Name of specific runtime to get
Returns:
AbstractRuntime: JavaScript runtime instance
"""
def runtimes():
"""
Return dictionary of all supported JavaScript runtimes.
Returns:
OrderedDict: Ordered dictionary mapping runtime names to runtime instances
"""
def register(name, runtime):
"""
Register a new JavaScript runtime.
Args:
name (str): Name to register the runtime under
runtime (AbstractRuntime): Runtime implementation instance
"""Work with compiled JavaScript contexts for efficient repeated execution.
# Context objects are returned by compile() - they cannot be directly instantiated
ctx = execjs.compile("var x = 1;")
# Context object methods:
def eval(source):
"""
Evaluate JavaScript code in the compiled context.
Args:
source (str): JavaScript source code to evaluate
Returns:
any: Result of JavaScript evaluation
"""
def exec_(source):
"""
Execute JavaScript code in context and return stdout output.
Args:
source (str): JavaScript source code to execute
Returns:
str: Standard output from JavaScript execution
"""
def call(name, *args):
"""
Call a JavaScript function by name with arguments.
Args:
name (str): Name of JavaScript function to call
*args: Arguments to pass to the function
Returns:
any: Result of function call
"""PyExecJS defines specific exception types for different error conditions:
class Error(Exception):
"""Base exception class for PyExecJS."""
class RuntimeError(Error):
"""Exception for runtime engine errors."""
class ProgramError(Error):
"""Exception for JavaScript program errors."""
class RuntimeUnavailableError(Error):
"""Exception when specified runtime is not available."""
class ProcessExitedWithNonZeroStatus(RuntimeError):
"""
Exception when external runtime process exits with non-zero status.
Not directly importable from execjs - available via execjs._exceptions.
"""
# Attributes: status, stdout, stderrConstants for specifying JavaScript runtime engines:
import execjs.runtime_names as runtime_names
# Available runtime constants
runtime_names.PyV8 # "PyV8"
runtime_names.Node # "Node"
runtime_names.JavaScriptCore # "JavaScriptCore"
runtime_names.SpiderMonkey # "SpiderMonkey"
runtime_names.JScript # "JScript"
runtime_names.PhantomJS # "PhantomJS"
runtime_names.SlimerJS # "SlimerJS"
runtime_names.Nashorn # "Nashorn"PyExecJS can be executed as a module for command-line JavaScript evaluation:
# Print available runtimes
python -m execjs --print-available-runtimes
# Evaluate JavaScript expression
python -m execjs -e "2 + 2"
# Use specific runtime
python -m execjs -r Node -e "console.log('Hello')"
# Load JavaScript files
python -m execjs script.js
# Set file encoding
python -m execjs --encoding utf-16 script.js
# Read from stdin
echo "2 + 2" | python -m execjs