Tool for interacting remotely with MicroPython devices
—
Interactive Read-Eval-Print Loop functionality with advanced features including output capture, code injection, escape sequence handling, and console management for seamless MicroPython development.
Enter interactive REPL mode with configurable options for output handling, capture, and code injection.
def do_repl(state, args):
"""
Enter interactive REPL mode.
Parameters:
- state: State object with active transport
- args: REPL configuration arguments
Args attributes:
- escape_non_printable: Boolean to escape non-printable characters
- capture: String path to capture session output to file
- inject_code: String of code to run when Ctrl-J is pressed
- inject_file: String path to file to run when Ctrl-K is pressed
"""Core REPL loop implementation handling console I/O, character processing, and special command injection.
def do_repl_main_loop(transport, console_in, console_out_real, *,
escape_non_printable, capture_file, inject_code, inject_file):
"""
Main REPL loop implementation.
Parameters:
- transport: Active transport connection to device
- console_in: Console input interface
- console_out_real: Console output interface
- escape_non_printable: Escape non-printable characters flag
- capture_file: File handle for session capture
- inject_code: Code string for Ctrl-J injection
- inject_file: File path for Ctrl-K injection
Handles bidirectional communication between console and device,
processes special key combinations, and manages output formatting.
"""Utility function to detect disconnection exceptions and handle connection loss gracefully.
def _is_disconnect_exception(exception):
"""
Check if exception indicates device disconnection.
Parameters:
- exception: Exception object to check
Returns:
- bool: True if exception indicates disconnection
Used for automatic reconnection and error handling.
"""# Enter REPL with default settings
mpremote repl
# REPL with non-printable character escaping
mpremote repl --escape-non-printable
# REPL with output capture
mpremote repl --capture session.log
# REPL with code injection setup
mpremote repl --inject-code "import gc; gc.collect()"
mpremote repl --inject-file debug.py# Connect and enter REPL
mpremote connect /dev/ttyUSB0 repl
# Auto-connect and REPL (default behavior)
mpremote
# REPL with specific device
mpremote a0 repl # shortcut for /dev/ttyACM0from mpremote.main import State
from mpremote.commands import do_repl
from mpremote.console import ConsolePosix # or ConsoleWindows
# Set up connected device state
state = State()
# ... connect to device ...
# Enter REPL with basic settings
args = type('Args', (), {
'escape_non_printable': False,
'capture': None,
'inject_code': None,
'inject_file': None
})()
do_repl(state, args)# Capture entire REPL session to file
mpremote repl --capture micropython_session.log
# Later review the captured session
cat micropython_session.log# Set up code injection for quick memory checks
mpremote repl --inject-code "
import micropython
print('Memory info:')
micropython.mem_info()
print('Free memory:', micropython.mem_free())
"
# Set up file injection for debugging utilities
echo "
def debug_info():
import sys, gc, micropython
print('Python version:', sys.version)
print('Free memory:', micropython.mem_free())
gc.collect()
print('After GC:', micropython.mem_free())
" > debug_utils.py
mpremote repl --inject-file debug_utils.pyThe REPL supports several special key combinations for enhanced functionality:
--inject-code)--inject-file)With --escape-non-printable, non-printable characters are displayed as escape sequences:
# Enable character escaping for debugging
mpremote repl --escape-non-printable
# Useful for viewing raw UART data or debugging protocol issuesSession capture records all input and output:
# Start REPL with capture
mpremote repl --capture session.log
# Session includes:
# - All typed commands
# - Device responses
# - Error messages
# - Injected code executionmpremote provides cross-platform console handling:
class ConsolePosix:
"""POSIX console interface for Unix-like systems"""
def init(self):
"""Initialize console for raw input"""
def deinit(self):
"""Restore normal console settings"""
def readchar(self):
"""Read single character from input"""
def cancel(self):
"""Cancel current input operation"""class ConsoleWindows:
"""Windows console interface"""
def init(self):
"""Initialize Windows console"""
def deinit(self):
"""Restore Windows console settings"""
def readchar(self):
"""Read single character from Windows console"""
def cancel(self):
"""Cancel Windows input operation"""# Interactive development with file injection
echo "
# Development utilities
def reload_module(module_name):
import sys
if module_name in sys.modules:
del sys.modules[module_name]
return __import__(module_name)
def run_tests():
import test_suite
test_suite.run_all()
" > dev_utils.py
mpremote mount . repl --inject-file dev_utils.py# Debugging with memory monitoring
mpremote repl --inject-code "
import micropython, gc
def mem_stats():
print(f'Free: {micropython.mem_free()} bytes')
print(f'Allocated: {micropython.mem_alloc()} bytes')
gc.collect()
print(f'After GC: {micropython.mem_free()} bytes')
mem_stats()
"# System administration REPL setup
mpremote repl --inject-code "
import os, sys, micropython
def sys_info():
print('System:', sys.platform)
print('Version:', sys.version)
print('Memory free:', micropython.mem_free())
print('Flash size:', os.statvfs('/')[0] * os.statvfs('/')[2])
print('Flash free:', os.statvfs('/')[0] * os.statvfs('/')[3])
sys_info()
"The REPL automatically detects and handles connection loss:
# Connection monitoring is built-in
# REPL will exit gracefully on disconnection
# Use with scripts for automatic recovery:
while True:
try:
mpremote.main() # Includes auto-connect + REPL
break
except TransportError:
print("Connection lost, retrying...")
time.sleep(1)# In REPL session, exceptions are handled gracefully:
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> # REPL continues normallyThe REPL is optimized for:
Install with Tessl CLI
npx tessl i tessl/pypi-mpremote