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

python-execution.mddocs/

0

# Python Code Execution

1

2

Jython provides multiple approaches for executing Python code from Java applications, ranging from simple script execution to full interactive interpreters.

3

4

## Direct Interpreter Usage

5

6

### PythonInterpreter

7

8

The main interface for embedding Python code execution in Java applications.

9

10

```java { .api }

11

public class PythonInterpreter implements AutoCloseable, Closeable {

12

// Constructors

13

public PythonInterpreter();

14

public PythonInterpreter(PyObject dict);

15

public PythonInterpreter(PyObject dict, PySystemState systemState);

16

public static PythonInterpreter threadLocalStateInterpreter(PyObject dict);

17

18

// Code execution

19

public void exec(String code);

20

public void exec(PyCode code);

21

public void execfile(String filename);

22

public PyObject eval(String code);

23

public PyObject eval(PyCode code);

24

25

// Variable management

26

public void set(String name, Object value);

27

public void set(String name, PyObject value);

28

public PyObject get(String name);

29

public PyObject get(String name, PyObject defaultValue);

30

31

// I/O management

32

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

33

public void setOut(PyObject outStream);

34

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

35

public void setErr(PyObject errStream);

36

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

37

public void setIn(PyObject inStream);

38

39

// Namespace management

40

public PyObject getLocals();

41

public void setLocals(PyObject locals);

42

public PyObject getGlobals();

43

public void setGlobals(PyObject globals);

44

45

// System state access

46

public PySystemState getSystemState();

47

48

// Resource management

49

public void close();

50

public void cleanup();

51

}

52

```

53

54

### Usage Examples

55

56

#### Basic Script Execution

57

58

```java

59

PythonInterpreter interp = new PythonInterpreter();

60

61

// Execute simple Python code

62

interp.exec("print('Hello, World!')");

63

interp.exec("x = 2 + 3");

64

65

// Get result

66

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

67

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

68

69

interp.close();

70

```

71

72

#### Variable Exchange

73

74

```java

75

PythonInterpreter interp = new PythonInterpreter();

76

77

// Set Java variables in Python

78

interp.set("name", "Alice");

79

interp.set("age", 30);

80

81

// Execute Python code using those variables

82

interp.exec("""

83

greeting = f"Hello, {name}! You are {age} years old."

84

birth_year = 2024 - age

85

""");

86

87

// Get results back to Java

88

String greeting = interp.get("greeting").toString();

89

int birthYear = interp.get("birth_year").asInt();

90

91

System.out.println(greeting); // Hello, Alice! You are 30 years old.

92

System.out.println(birthYear); // 1994

93

94

interp.close();

95

```

96

97

#### File Execution

98

99

```java

100

PythonInterpreter interp = new PythonInterpreter();

101

102

// Execute Python file

103

interp.execfile("/path/to/script.py");

104

105

// Access variables defined in the file

106

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

107

108

interp.close();

109

```

110

111

## Interactive Interpreter

112

113

### InteractiveInterpreter

114

115

Supports interactive Python console functionality with proper handling of incomplete statements.

116

117

```java { .api }

118

public class InteractiveInterpreter extends PythonInterpreter {

119

public InteractiveInterpreter();

120

public InteractiveInterpreter(PyObject locals);

121

public InteractiveInterpreter(PyObject locals, PySystemState systemState);

122

123

// Interactive execution

124

public boolean runsource(String source);

125

public boolean runsource(String source, String filename);

126

public boolean runsource(String source, String filename, CompileMode mode);

127

128

// Code execution

129

public void runcode(PyObject code);

130

131

// Compilation

132

public PyCode compile(String source, String filename, CompileMode mode);

133

134

// Error handling for interactive use

135

public void showexception(PyException exc);

136

public void showtraceback();

137

public void showsyntaxerror(String filename);

138

139

// Output methods

140

public void write(String data);

141

142

// Buffer management

143

public StringBuilder buffer;

144

public void resetbuffer();

145

146

// Debugging support

147

public void interrupt(ThreadState ts);

148

}

149

```

150

151

### Usage Examples

152

153

#### Interactive Code Execution

154

155

```java

156

InteractiveInterpreter interp = new InteractiveInterpreter();

157

158

// Returns true if more input is needed (incomplete statement)

159

boolean needsMore = interp.runsource("if True:");

160

System.out.println(needsMore); // true

161

162

// Complete the statement

163

needsMore = interp.runsource(" print('Complete!')");

164

System.out.println(needsMore); // false - statement executed

165

166

interp.close();

167

```

168

169

## Interactive Console

170

171

### InteractiveConsole

172

173

Complete interactive Python console with input/output handling.

174

175

```java { .api }

176

public class InteractiveConsole extends InteractiveInterpreter {

177

public InteractiveConsole();

178

public InteractiveConsole(PyObject locals);

179

public InteractiveConsole(PyObject locals, String filename);

180

181

// Console interaction

182

public void interact();

183

public void interact(String banner);

184

public String raw_input();

185

public String raw_input(PyObject prompt);

186

187

// Input handling

188

public boolean push(String line);

189

public void resetbuffer();

190

}

191

```

192

193

### Usage Examples

194

195

#### Console Session

196

197

```java

198

InteractiveConsole console = new InteractiveConsole();

199

200

// Start interactive session with custom banner

201

console.interact("Welcome to Jython Console!");

202

203

// This will start an interactive Python REPL that accepts input

204

// and provides output until the user exits

205

```

206

207

## Code Compilation

208

209

### PyCode Objects

210

211

Represent compiled Python code that can be executed multiple times.

212

213

```java { .api }

214

public abstract class PyCode extends PyObject {

215

public abstract PyObject call(ThreadState ts, PyFrame frame);

216

public PyObject call(PyObject globals);

217

public PyObject call(PyObject globals, PyObject locals);

218

}

219

220

// Factory methods in Py class

221

public final class Py {

222

public static PyCode newCode(int argcount, String varnames[],

223

String filename, String name,

224

boolean args, boolean keywords,

225

PyFunctionTable funcs, int func_id);

226

public static PyCode newJavaCode(Class<?> cls, String name);

227

}

228

```

229

230

### Usage Examples

231

232

#### Pre-compiled Code Execution

233

234

```java

235

PythonInterpreter interp = new PythonInterpreter();

236

237

// Compile code once

238

PyCode code = interp.compile("result = x * y + z", "<string>", CompileMode.exec);

239

240

// Execute multiple times with different variables

241

interp.set("x", 2);

242

interp.set("y", 3);

243

interp.set("z", 4);

244

interp.eval(code);

245

System.out.println(interp.get("result")); // 10

246

247

interp.set("x", 5);

248

interp.set("y", 6);

249

interp.set("z", 7);

250

interp.eval(code);

251

System.out.println(interp.get("result")); // 37

252

253

interp.close();

254

```

255

256

## Initialization and Configuration

257

258

### System Initialization

259

260

```java { .api }

261

public class PythonInterpreter {

262

public static void initialize(Properties preProperties,

263

Properties postProperties,

264

String[] argv);

265

}

266

```

267

268

### Usage Examples

269

270

#### Custom Initialization

271

272

```java

273

Properties preProps = new Properties();

274

preProps.setProperty("python.home", "/path/to/jython");

275

276

Properties postProps = new Properties();

277

postProps.setProperty("python.path", "/path/to/modules:/another/path");

278

279

String[] args = {"arg1", "arg2"};

280

281

PythonInterpreter.initialize(preProps, postProps, args);

282

283

PythonInterpreter interp = new PythonInterpreter();

284

// Interpreter now uses custom configuration

285

interp.close();

286

```

287

288

## Thread Safety

289

290

### Thread-Local Interpreters

291

292

```java { .api }

293

public class PythonInterpreter {

294

public static PythonInterpreter threadLocalStateInterpreter(PyObject dict);

295

}

296

```

297

298

### Usage Examples

299

300

#### Multi-threaded Environment

301

302

```java

303

// Create thread-local interpreter

304

PythonInterpreter interp = PythonInterpreter.threadLocalStateInterpreter(null);

305

306

// Each thread gets its own interpreter instance

307

// Safe for concurrent use across threads

308

interp.exec("print('Thread:', threading.current_thread().name)");

309

310

interp.close();

311

```

312

313

## Resource Management

314

315

### Proper Cleanup

316

317

```java

318

// Try-with-resources (recommended)

319

try (PythonInterpreter interp = new PythonInterpreter()) {

320

interp.exec("print('Hello, World!')");

321

// Automatically closed

322

}

323

324

// Manual cleanup

325

PythonInterpreter interp = new PythonInterpreter();

326

try {

327

interp.exec("print('Hello, World!')");

328

} finally {

329

interp.close();

330

}

331

```

332

333

## Error Handling

334

335

All execution methods can throw `PyException` for Python runtime errors:

336

337

```java

338

try {

339

interp.exec("undefined_variable");

340

} catch (PyException e) {

341

if (e.match(Py.NameError)) {

342

System.out.println("Variable not found: " + e.value);

343

}

344

}

345

```