Run JavaScript code from Python with automatic runtime selection
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core functionality for evaluating and executing JavaScript code from Python applications.
PyExecJS provides three main execution modes: evaluation (returning results), execution (returning output), and compilation (creating reusable contexts). All functions automatically select the best available JavaScript runtime unless specifically configured.
Evaluate JavaScript expressions and return the computed result.
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 (int, float, str, bool, list, dict, or None)
Raises:
ProgramError: When JavaScript code contains syntax or runtime errors
RuntimeError: When JavaScript runtime engine encounters errors
RuntimeUnavailableError: When no JavaScript runtime is available
"""Execute JavaScript code and return the standard output.
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
Raises:
ProgramError: When JavaScript code contains syntax or runtime errors
RuntimeError: When JavaScript runtime engine encounters errors
RuntimeUnavailableError: When no JavaScript runtime is available
"""Compile JavaScript source code into a reusable execution context.
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 with eval(), exec_(), and call() methods
Raises:
ProgramError: When JavaScript code contains syntax errors
RuntimeError: When JavaScript runtime engine encounters errors
RuntimeUnavailableError: When no JavaScript runtime is available
"""import execjs
# Simple expressions
result = execjs.eval("2 + 3 * 4") # 14
name = execjs.eval("'Hello'.toUpperCase()") # "HELLO"
# Complex objects
data = execjs.eval("({name: 'John', age: 30, scores: [85, 92, 78]})")
# Returns: {'name': 'John', 'age': 30, 'scores': [85, 92, 78]}import execjs
# Console output
output = execjs.exec_("console.log('Processing...'); console.log('Done!')")
# Returns: "Processing...\nDone!\n"
# Multiple statements
code = """
for (var i = 1; i <= 3; i++) {
console.log('Step ' + i);
}
"""
output = execjs.exec_(code)
# Returns: "Step 1\nStep 2\nStep 3\n"import execjs
# Compile JavaScript with functions
js_code = """
var math = {
add: function(a, b) { return a + b; },
multiply: function(a, b) { return a * b; },
factorial: function(n) {
if (n <= 1) return 1;
return n * this.factorial(n - 1);
}
};
"""
ctx = execjs.compile(js_code)
# Use compiled context multiple times
result1 = ctx.call("math.add", 5, 3) # 8
result2 = ctx.call("math.multiply", 4, 7) # 28
result3 = ctx.call("math.factorial", 5) # 120All execution functions support specifying a working directory for JavaScript execution:
import execjs
import os
# Execute in specific directory
result = execjs.eval("typeof require !== 'undefined'", cwd="/path/to/node/project")
# Useful for Node.js modules that depend on relative paths
ctx = execjs.compile("var fs = require('fs');", cwd="/home/user/project")PyExecJS automatically converts between JavaScript and Python types:
| JavaScript Type | Python Type |
|---|---|
number | int or float |
string | str |
boolean | bool |
null | None |
undefined | None |
Array | list |
Object | dict |
import execjs
try:
result = execjs.eval("invalidSyntax(")
except execjs.ProgramError as e:
print(f"JavaScript error: {e}")
try:
result = execjs.eval("throw new Error('Custom error')")
except execjs.ProgramError as e:
print(f"JavaScript threw: {e}")
try:
# This will fail if no runtime is available
result = execjs.eval("2 + 2")
except execjs.RuntimeUnavailableError as e:
print(f"No JavaScript runtime available: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-pyexecjs