or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

context-handling.mdindex.mdjavascript-execution.mdruntime-management.md

index.mddocs/

0

# PyExecJS

1

2

JavaScript execution bridge for Python applications.

3

4

## Overview

5

6

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.

7

8

## Package Information

9

10

- **Name**: PyExecJS

11

- **Type**: Python library package

12

- **Language**: Python

13

- **Version**: 1.5.1 (End of Life)

14

- **Installation**: `pip install PyExecJS`

15

16

## Core Imports

17

18

```python { .api }

19

import execjs

20

21

# For runtime classes and exceptions (based on __all__ exports)

22

from execjs import ExternalRuntime

23

from execjs import Error, RuntimeError, ProgramError, RuntimeUnavailableError

24

25

# For runtime name constants (must import directly from submodule)

26

import execjs.runtime_names as runtime_names

27

```

28

29

## Basic Usage

30

31

Simple JavaScript evaluation from Python:

32

33

```python

34

import execjs

35

36

# Evaluate JavaScript expression

37

result = execjs.eval("2 + 2")

38

print(result) # 4

39

40

# Execute JavaScript code with output

41

output = execjs.exec_("console.log('Hello from JavaScript')")

42

print(output) # "Hello from JavaScript\n"

43

44

# Compile and reuse JavaScript context

45

ctx = execjs.compile("var add = function(a, b) { return a + b; }")

46

result = ctx.call("add", 3, 4)

47

print(result) # 7

48

```

49

50

## Architecture

51

52

PyExecJS operates through three main layers:

53

54

1. **High-level API**: Simple functions for quick JavaScript evaluation (`eval`, `exec_`, `compile`)

55

2. **Runtime Management**: Automatic or manual selection of available JavaScript engines

56

3. **Runtime Implementations**: Platform-specific JavaScript execution engines

57

58

## Capabilities

59

60

### JavaScript Execution

61

62

Core functionality for evaluating and executing JavaScript code from Python.

63

64

```python { .api }

65

def eval(source, cwd=None):

66

"""

67

Evaluate JavaScript source code and return the result.

68

69

Args:

70

source (str): JavaScript source code to evaluate

71

cwd (str, optional): Working directory for execution

72

73

Returns:

74

any: Result of JavaScript evaluation

75

"""

76

77

def exec_(source, cwd=None):

78

"""

79

Execute JavaScript source code and return stdout output.

80

81

Args:

82

source (str): JavaScript source code to execute

83

cwd (str, optional): Working directory for execution

84

85

Returns:

86

str: Standard output from JavaScript execution

87

"""

88

89

def compile(source, cwd=None):

90

"""

91

Compile JavaScript source into a reusable context object.

92

93

Args:

94

source (str): JavaScript source code to compile

95

cwd (str, optional): Working directory for compilation

96

97

Returns:

98

Context object: Compiled JavaScript execution context

99

"""

100

```

101

102

[JavaScript Execution](./javascript-execution.md)

103

104

### Runtime Management

105

106

Manage JavaScript runtime environments and automatic runtime selection.

107

108

```python { .api }

109

def get(name=None):

110

"""

111

Get a JavaScript runtime by name or automatically select one.

112

113

Args:

114

name (str, optional): Name of specific runtime to get

115

116

Returns:

117

AbstractRuntime: JavaScript runtime instance

118

"""

119

120

def runtimes():

121

"""

122

Return dictionary of all supported JavaScript runtimes.

123

124

Returns:

125

OrderedDict: Ordered dictionary mapping runtime names to runtime instances

126

"""

127

128

def register(name, runtime):

129

"""

130

Register a new JavaScript runtime.

131

132

Args:

133

name (str): Name to register the runtime under

134

runtime (AbstractRuntime): Runtime implementation instance

135

"""

136

```

137

138

[Runtime Management](./runtime-management.md)

139

140

### Context Handling

141

142

Work with compiled JavaScript contexts for efficient repeated execution.

143

144

```python { .api }

145

# Context objects are returned by compile() - they cannot be directly instantiated

146

ctx = execjs.compile("var x = 1;")

147

148

# Context object methods:

149

def eval(source):

150

"""

151

Evaluate JavaScript code in the compiled context.

152

153

Args:

154

source (str): JavaScript source code to evaluate

155

156

Returns:

157

any: Result of JavaScript evaluation

158

"""

159

160

def exec_(source):

161

"""

162

Execute JavaScript code in context and return stdout output.

163

164

Args:

165

source (str): JavaScript source code to execute

166

167

Returns:

168

str: Standard output from JavaScript execution

169

"""

170

171

def call(name, *args):

172

"""

173

Call a JavaScript function by name with arguments.

174

175

Args:

176

name (str): Name of JavaScript function to call

177

*args: Arguments to pass to the function

178

179

Returns:

180

any: Result of function call

181

"""

182

```

183

184

[Context Handling](./context-handling.md)

185

186

## Exception Handling

187

188

PyExecJS defines specific exception types for different error conditions:

189

190

```python { .api }

191

class Error(Exception):

192

"""Base exception class for PyExecJS."""

193

194

class RuntimeError(Error):

195

"""Exception for runtime engine errors."""

196

197

class ProgramError(Error):

198

"""Exception for JavaScript program errors."""

199

200

class RuntimeUnavailableError(Error):

201

"""Exception when specified runtime is not available."""

202

203

class ProcessExitedWithNonZeroStatus(RuntimeError):

204

"""

205

Exception when external runtime process exits with non-zero status.

206

Not directly importable from execjs - available via execjs._exceptions.

207

"""

208

# Attributes: status, stdout, stderr

209

```

210

211

## Runtime Names

212

213

Constants for specifying JavaScript runtime engines:

214

215

```python { .api }

216

import execjs.runtime_names as runtime_names

217

218

# Available runtime constants

219

runtime_names.PyV8 # "PyV8"

220

runtime_names.Node # "Node"

221

runtime_names.JavaScriptCore # "JavaScriptCore"

222

runtime_names.SpiderMonkey # "SpiderMonkey"

223

runtime_names.JScript # "JScript"

224

runtime_names.PhantomJS # "PhantomJS"

225

runtime_names.SlimerJS # "SlimerJS"

226

runtime_names.Nashorn # "Nashorn"

227

```

228

229

## Environment Variables

230

231

- **EXECJS_RUNTIME**: Specify default JavaScript runtime to use

232

233

## Command Line Interface

234

235

PyExecJS can be executed as a module for command-line JavaScript evaluation:

236

237

```bash

238

# Print available runtimes

239

python -m execjs --print-available-runtimes

240

241

# Evaluate JavaScript expression

242

python -m execjs -e "2 + 2"

243

244

# Use specific runtime

245

python -m execjs -r Node -e "console.log('Hello')"

246

247

# Load JavaScript files

248

python -m execjs script.js

249

250

# Set file encoding

251

python -m execjs --encoding utf-16 script.js

252

253

# Read from stdin

254

echo "2 + 2" | python -m execjs

255

```