or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-reference.mdcode-execution.mddevice-config.mddevice-connection.mdfilesystem.mdindex.mdmounting.mdpackage-management.mdrepl.mdromfs.md

repl.mddocs/

0

# REPL Interface

1

2

Interactive Read-Eval-Print Loop functionality with advanced features including output capture, code injection, escape sequence handling, and console management for seamless MicroPython development.

3

4

## Capabilities

5

6

### Main REPL Interface

7

8

Enter interactive REPL mode with configurable options for output handling, capture, and code injection.

9

10

```python { .api }

11

def do_repl(state, args):

12

"""

13

Enter interactive REPL mode.

14

15

Parameters:

16

- state: State object with active transport

17

- args: REPL configuration arguments

18

19

Args attributes:

20

- escape_non_printable: Boolean to escape non-printable characters

21

- capture: String path to capture session output to file

22

- inject_code: String of code to run when Ctrl-J is pressed

23

- inject_file: String path to file to run when Ctrl-K is pressed

24

"""

25

```

26

27

### REPL Main Loop

28

29

Core REPL loop implementation handling console I/O, character processing, and special command injection.

30

31

```python { .api }

32

def do_repl_main_loop(transport, console_in, console_out_real, *,

33

escape_non_printable, capture_file, inject_code, inject_file):

34

"""

35

Main REPL loop implementation.

36

37

Parameters:

38

- transport: Active transport connection to device

39

- console_in: Console input interface

40

- console_out_real: Console output interface

41

- escape_non_printable: Escape non-printable characters flag

42

- capture_file: File handle for session capture

43

- inject_code: Code string for Ctrl-J injection

44

- inject_file: File path for Ctrl-K injection

45

46

Handles bidirectional communication between console and device,

47

processes special key combinations, and manages output formatting.

48

"""

49

```

50

51

### Connection Status Checking

52

53

Utility function to detect disconnection exceptions and handle connection loss gracefully.

54

55

```python { .api }

56

def _is_disconnect_exception(exception):

57

"""

58

Check if exception indicates device disconnection.

59

60

Parameters:

61

- exception: Exception object to check

62

63

Returns:

64

- bool: True if exception indicates disconnection

65

66

Used for automatic reconnection and error handling.

67

"""

68

```

69

70

## Command-Line Interface

71

72

### Basic REPL Usage

73

74

```bash

75

# Enter REPL with default settings

76

mpremote repl

77

78

# REPL with non-printable character escaping

79

mpremote repl --escape-non-printable

80

81

# REPL with output capture

82

mpremote repl --capture session.log

83

84

# REPL with code injection setup

85

mpremote repl --inject-code "import gc; gc.collect()"

86

mpremote repl --inject-file debug.py

87

```

88

89

### REPL with Device Connection

90

91

```bash

92

# Connect and enter REPL

93

mpremote connect /dev/ttyUSB0 repl

94

95

# Auto-connect and REPL (default behavior)

96

mpremote

97

98

# REPL with specific device

99

mpremote a0 repl # shortcut for /dev/ttyACM0

100

```

101

102

## Usage Examples

103

104

### Interactive Development Session

105

106

```python

107

from mpremote.main import State

108

from mpremote.commands import do_repl

109

from mpremote.console import ConsolePosix # or ConsoleWindows

110

111

# Set up connected device state

112

state = State()

113

# ... connect to device ...

114

115

# Enter REPL with basic settings

116

args = type('Args', (), {

117

'escape_non_printable': False,

118

'capture': None,

119

'inject_code': None,

120

'inject_file': None

121

})()

122

do_repl(state, args)

123

```

124

125

### REPL with Session Capture

126

127

```bash

128

# Capture entire REPL session to file

129

mpremote repl --capture micropython_session.log

130

131

# Later review the captured session

132

cat micropython_session.log

133

```

134

135

### Code Injection Features

136

137

```bash

138

# Set up code injection for quick memory checks

139

mpremote repl --inject-code "

140

import micropython

141

print('Memory info:')

142

micropython.mem_info()

143

print('Free memory:', micropython.mem_free())

144

"

145

146

# Set up file injection for debugging utilities

147

echo "

148

def debug_info():

149

import sys, gc, micropython

150

print('Python version:', sys.version)

151

print('Free memory:', micropython.mem_free())

152

gc.collect()

153

print('After GC:', micropython.mem_free())

154

" > debug_utils.py

155

156

mpremote repl --inject-file debug_utils.py

157

```

158

159

## Special Key Combinations

160

161

The REPL supports several special key combinations for enhanced functionality:

162

163

### Built-in Key Combinations

164

165

- **Ctrl-C**: Interrupt/KeyboardInterrupt

166

- **Ctrl-D**: Soft reset (restart MicroPython)

167

- **Ctrl-E**: Enter paste mode for multi-line code

168

- **Ctrl-F**: Exit paste mode

169

170

### Injection Key Combinations

171

172

- **Ctrl-J**: Execute injected code string (from `--inject-code`)

173

- **Ctrl-K**: Execute injected file (from `--inject-file`)

174

175

### Exit REPL

176

177

- **Ctrl-X**: Exit REPL and return to command line

178

179

## Output Handling

180

181

### Character Escaping

182

183

With `--escape-non-printable`, non-printable characters are displayed as escape sequences:

184

185

```bash

186

# Enable character escaping for debugging

187

mpremote repl --escape-non-printable

188

189

# Useful for viewing raw UART data or debugging protocol issues

190

```

191

192

### Session Capture

193

194

Session capture records all input and output:

195

196

```bash

197

# Start REPL with capture

198

mpremote repl --capture session.log

199

200

# Session includes:

201

# - All typed commands

202

# - Device responses

203

# - Error messages

204

# - Injected code execution

205

```

206

207

## Console Management

208

209

mpremote provides cross-platform console handling:

210

211

### POSIX/Unix Console

212

213

```python { .api }

214

class ConsolePosix:

215

"""POSIX console interface for Unix-like systems"""

216

217

def init(self):

218

"""Initialize console for raw input"""

219

220

def deinit(self):

221

"""Restore normal console settings"""

222

223

def readchar(self):

224

"""Read single character from input"""

225

226

def cancel(self):

227

"""Cancel current input operation"""

228

```

229

230

### Windows Console

231

232

```python { .api }

233

class ConsoleWindows:

234

"""Windows console interface"""

235

236

def init(self):

237

"""Initialize Windows console"""

238

239

def deinit(self):

240

"""Restore Windows console settings"""

241

242

def readchar(self):

243

"""Read single character from Windows console"""

244

245

def cancel(self):

246

"""Cancel Windows input operation"""

247

```

248

249

## Advanced Usage Patterns

250

251

### Development Workflow Integration

252

253

```bash

254

# Interactive development with file injection

255

echo "

256

# Development utilities

257

def reload_module(module_name):

258

import sys

259

if module_name in sys.modules:

260

del sys.modules[module_name]

261

return __import__(module_name)

262

263

def run_tests():

264

import test_suite

265

test_suite.run_all()

266

" > dev_utils.py

267

268

mpremote mount . repl --inject-file dev_utils.py

269

```

270

271

### Debugging Session

272

273

```bash

274

# Debugging with memory monitoring

275

mpremote repl --inject-code "

276

import micropython, gc

277

def mem_stats():

278

print(f'Free: {micropython.mem_free()} bytes')

279

print(f'Allocated: {micropython.mem_alloc()} bytes')

280

gc.collect()

281

print(f'After GC: {micropython.mem_free()} bytes')

282

mem_stats()

283

"

284

```

285

286

### Remote System Administration

287

288

```bash

289

# System administration REPL setup

290

mpremote repl --inject-code "

291

import os, sys, micropython

292

def sys_info():

293

print('System:', sys.platform)

294

print('Version:', sys.version)

295

print('Memory free:', micropython.mem_free())

296

print('Flash size:', os.statvfs('/')[0] * os.statvfs('/')[2])

297

print('Flash free:', os.statvfs('/')[0] * os.statvfs('/')[3])

298

sys_info()

299

"

300

```

301

302

## Error Handling and Recovery

303

304

### Connection Loss Handling

305

306

The REPL automatically detects and handles connection loss:

307

308

```python

309

# Connection monitoring is built-in

310

# REPL will exit gracefully on disconnection

311

# Use with scripts for automatic recovery:

312

313

while True:

314

try:

315

mpremote.main() # Includes auto-connect + REPL

316

break

317

except TransportError:

318

print("Connection lost, retrying...")

319

time.sleep(1)

320

```

321

322

### Exception Handling in REPL

323

324

```python

325

# In REPL session, exceptions are handled gracefully:

326

>>> 1/0

327

Traceback (most recent call last):

328

File "<stdin>", line 1, in <module>

329

ZeroDivisionError: division by zero

330

>>> # REPL continues normally

331

```

332

333

## Performance and Responsiveness

334

335

The REPL is optimized for:

336

337

- **Low latency**: Immediate character echo and response

338

- **Efficient I/O**: Minimal buffering for real-time interaction

339

- **Cross-platform**: Consistent behavior across operating systems

340

- **Resource usage**: Minimal memory footprint on host system