CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyexecjs

Run JavaScript code from Python with automatic runtime selection

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

index.mddocs/

PyExecJS

JavaScript execution bridge for Python applications.

Overview

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.

Package Information

  • Name: PyExecJS
  • Type: Python library package
  • Language: Python
  • Version: 1.5.1 (End of Life)
  • Installation: pip install PyExecJS

Core Imports

import 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_names

Basic Usage

Simple 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)  # 7

Architecture

PyExecJS operates through three main layers:

  1. High-level API: Simple functions for quick JavaScript evaluation (eval, exec_, compile)
  2. Runtime Management: Automatic or manual selection of available JavaScript engines
  3. Runtime Implementations: Platform-specific JavaScript execution engines

Capabilities

JavaScript Execution

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
    """

JavaScript Execution

Runtime Management

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
    """

Runtime Management

Context Handling

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
    """

Context Handling

Exception Handling

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, stderr

Runtime Names

Constants 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"

Environment Variables

  • EXECJS_RUNTIME: Specify default JavaScript runtime to use

Command Line Interface

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

Install with Tessl CLI

npx tessl i tessl/pypi-pyexecjs

docs

context-handling.md

index.md

javascript-execution.md

runtime-management.md

tile.json