or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdexception-handling.mdindex.mdjava-integration.mdjsr223-scripting.mdpython-execution.mdpython-objects.md

index.mddocs/

0

# Jython

1

2

Jython is an implementation of Python 2.7 written in 100% Pure Java that provides seamless integration with the Java platform and ecosystem. It enables Python code execution on any Java Virtual Machine while offering access to Java libraries and frameworks directly from Python code. Jython serves as a bridge technology allowing Python developers to leverage Java's extensive ecosystem while maintaining Python's syntax and semantics.

3

4

## Package Information

5

6

- **Package Name**: org.python:jython-standalone

7

- **Package Type**: maven

8

- **Language**: Java

9

- **Installation**:

10

```xml

11

<dependency>

12

<groupId>org.python</groupId>

13

<artifactId>jython-standalone</artifactId>

14

<version>2.7.4</version>

15

</dependency>

16

```

17

18

## Core Imports

19

20

```java

21

import org.python.util.PythonInterpreter;

22

import org.python.core.*;

23

import org.python.jsr223.PyScriptEngineFactory;

24

import javax.script.ScriptEngine;

25

```

26

27

## Basic Usage

28

29

```java

30

import org.python.util.PythonInterpreter;

31

import org.python.core.*;

32

33

public class JythonExample {

34

public static void main(String[] args) {

35

// Initialize Jython

36

PythonInterpreter.initialize(System.getProperties(),

37

System.getProperties(),

38

new String[0]);

39

40

// Create interpreter

41

PythonInterpreter interp = new PythonInterpreter();

42

43

// Execute Python code

44

interp.exec("print('Hello from Python!')");

45

46

// Set variables from Java

47

interp.set("x", 42);

48

interp.exec("y = x * 2");

49

50

// Get results back to Java

51

PyObject result = interp.get("y");

52

System.out.println("Result: " + result.asInt());

53

54

interp.close();

55

}

56

}

57

```

58

59

## Architecture

60

61

Jython's architecture consists of several key components:

62

63

- **Core Runtime**: Python object system implemented in Java (`org.python.core.*`)

64

- **Embedding API**: High-level interfaces for embedding Python in Java applications (`org.python.util.*`)

65

- **JSR-223 Support**: Standard Java scripting API compliance (`org.python.jsr223.*`)

66

- **Type System**: Complete Python type hierarchy with Java integration

67

- **Object Factory**: Centralized creation and conversion utilities (`Py` class)

68

- **System State**: Python environment and module management (`PySystemState`)

69

70

## Capabilities

71

72

### Python Code Execution

73

74

Execute Python code directly from Java applications using multiple approaches: direct interpreter, interactive console, or JSR-223 scripting engine.

75

76

```java { .api }

77

public class PythonInterpreter implements AutoCloseable, Closeable {

78

// Constructors

79

public PythonInterpreter();

80

public PythonInterpreter(PyObject dict);

81

public PythonInterpreter(PyObject dict, PySystemState systemState);

82

public static PythonInterpreter threadLocalStateInterpreter(PyObject dict);

83

84

// Code execution

85

public void exec(String code);

86

public void exec(PyObject code);

87

public PyObject eval(String code);

88

public PyObject eval(PyObject code);

89

public void execfile(String filename);

90

public void execfile(java.io.InputStream s);

91

public void execfile(java.io.InputStream s, String name);

92

93

// Variable management

94

public void set(String name, Object value);

95

public void set(String name, PyObject value);

96

public PyObject get(String name);

97

public <T> T get(String name, Class<T> javaclass);

98

99

// I/O management

100

public void setIn(PyObject inStream);

101

public void setIn(java.io.Reader inStream);

102

public void setIn(java.io.InputStream inStream);

103

public void setOut(PyObject outStream);

104

public void setOut(java.io.Writer outStream);

105

public void setOut(java.io.OutputStream outStream);

106

public void setErr(PyObject outStream);

107

public void setErr(java.io.Writer outStream);

108

public void setErr(java.io.OutputStream outStream);

109

110

// Namespace management

111

public PyObject getLocals();

112

public void setLocals(PyObject d);

113

public PyObject getGlobals();

114

public PySystemState getSystemState();

115

116

// Code compilation

117

public PyCode compile(String script);

118

public PyCode compile(Reader reader);

119

public PyCode compile(String script, String filename);

120

public PyCode compile(Reader reader, String filename);

121

122

// Resource management

123

public void close();

124

public void cleanup();

125

126

// Initialization

127

public static void initialize(Properties preProperties, Properties postProperties, String[] argv);

128

}

129

```

130

131

[Python Code Execution](./python-execution.md)

132

133

### Python Object Creation and Manipulation

134

135

Create, manipulate, and convert Python objects from Java using the comprehensive factory methods and object hierarchy.

136

137

```java { .api }

138

public final class Py {

139

// Object creation

140

public static PyInteger newInteger(int i);

141

public static PyObject newInteger(long i);

142

public static PyLong newLong(String s);

143

public static PyLong newLong(java.math.BigInteger i);

144

public static PyLong newLong(int i);

145

public static PyLong newLong(long l);

146

public static PyFloat newFloat(float v);

147

public static PyFloat newFloat(double v);

148

public static PyString newString(char c);

149

public static PyString newString(String s);

150

public static PyUnicode newUnicode(char c);

151

public static PyUnicode newUnicode(String s);

152

public static PyBoolean newBoolean(boolean t);

153

public static PyStringMap newStringMap();

154

155

// Type conversion

156

public static PyObject java2py(Object o);

157

public static PyString java2py(String s);

158

public static PyInteger java2py(int i);

159

public static PyInteger java2py(long l);

160

public static PyFloat java2py(float f);

161

public static PyFloat java2py(double d);

162

public static PyBoolean java2py(boolean b);

163

}

164

165

public class PyObject implements Serializable {

166

public PyObject __call__(PyObject args[]);

167

public PyObject __getattr__(String name);

168

public void __setattr__(String name, PyObject value);

169

public Object __tojava__(Class<?> c);

170

}

171

172

// Collection constructors (no factory methods available)

173

public class PyList extends PySequenceList {

174

public PyList();

175

public PyList(PyObject[] elements);

176

public PyList(Collection<?> c);

177

}

178

179

public class PyDictionary extends PyObject {

180

public PyDictionary();

181

public PyDictionary(Map<PyObject, PyObject> map);

182

public PyDictionary(PyObject elements[]);

183

}

184

```

185

186

[Python Objects](./python-objects.md)

187

188

### Java-Python Integration

189

190

Bridge between Java and Python types with automatic conversion, method invocation, and exception handling.

191

192

```java { .api }

193

public class PyObject implements Serializable {

194

public Object __tojava__(Class<?> c);

195

public String toString();

196

public boolean equals(Object o);

197

public int hashCode();

198

}

199

200

// Built-in Python types

201

public class PyString extends PyBaseString {

202

public String getString();

203

public PyString(String string);

204

}

205

206

public class PyList extends PySequenceList {

207

public void append(PyObject o);

208

public PyObject pop();

209

public int size();

210

}

211

```

212

213

[Java-Python Integration](./java-integration.md)

214

215

### JSR-223 Scripting Engine

216

217

Use Jython through the standard Java scripting API for seamless integration with existing Java applications that support JSR-223.

218

219

```java { .api }

220

public class PyScriptEngineFactory implements ScriptEngineFactory {

221

public String getEngineName();

222

public String getLanguageVersion();

223

public ScriptEngine getScriptEngine();

224

}

225

226

public class PyScriptEngine extends AbstractScriptEngine

227

implements Compilable, Invocable, AutoCloseable {

228

public Object eval(String script, ScriptContext context);

229

public CompiledScript compile(String script);

230

public Object invokeFunction(String name, Object... args);

231

}

232

```

233

234

[JSR-223 Scripting](./jsr223-scripting.md)

235

236

### System Configuration and Options

237

238

Configure Jython runtime behavior, system state, Python path, and various performance and debugging options.

239

240

```java { .api }

241

public class PySystemState extends PyObject {

242

public static void initialize(Properties preProperties, Properties postProperties, String[] argv);

243

public static PySystemState getDefault();

244

public PyList path; // Python module search path

245

public PyList argv; // Command line arguments

246

public PyDictionary modules; // Loaded modules cache

247

}

248

249

public class Options {

250

public static boolean showJavaExceptions;

251

public static boolean respectJavaAccessibility;

252

public static int verbose;

253

public static boolean debug;

254

}

255

```

256

257

[Configuration](./configuration.md)

258

259

### Exception Handling

260

261

Handle Python exceptions in Java code with comprehensive exception types and conversion utilities.

262

263

```java { .api }

264

public class PyException extends RuntimeException {

265

public PyObject type; // Exception type

266

public PyObject value; // Exception value

267

public PyTraceback traceback; // Python traceback

268

269

public PyException(PyObject type, String value);

270

public boolean match(PyObject exc);

271

public void normalize();

272

}

273

274

// Exception factory methods in Py class

275

public final class Py {

276

public static PyException TypeError(String message);

277

public static PyException ValueError(String message);

278

public static PyException RuntimeError(String message);

279

public static PyException AttributeError(String message);

280

}

281

```

282

283

[Exception Handling](./exception-handling.md)

284

285

## Types

286

287

```java { .api }

288

// Base class for all Python objects

289

public class PyObject implements Serializable {

290

public PyType getType();

291

public boolean isCallable();

292

public boolean isSequenceType();

293

public boolean isMappingType();

294

public boolean isNumberType();

295

296

// Python protocol methods

297

public PyObject __add__(PyObject other);

298

public PyObject __getitem__(PyObject key);

299

public PyObject __iter__();

300

public String __str__();

301

public String __repr__();

302

}

303

304

// System state management

305

public class PySystemState extends PyObject {

306

public PyList path;

307

public PyList argv;

308

public PyDictionary modules;

309

public PyObject stdin;

310

public PyObject stdout;

311

public PyObject stderr;

312

}

313

314

// Main embedding interface

315

public class PythonInterpreter implements AutoCloseable, Closeable {

316

public void set(String name, Object value);

317

public PyObject get(String name);

318

public PyObject getLocals();

319

public PyObject getGlobals();

320

public PySystemState getSystemState();

321

}

322

```