Tool for interacting remotely with MicroPython devices
—
Execute Python code on MicroPython devices with support for expressions, multi-line statements, and local script execution with real-time output streaming.
Execute Python code strings on MicroPython devices with optional output following and error handling.
def do_exec(state, args):
"""
Execute Python code string on device.
Parameters:
- state: State object with active transport
- args: Arguments containing code expression and options
Args attributes:
- expr: List containing code string to execute
- follow: Boolean to follow output until completion (default True)
"""Evaluate Python expressions and print the result, useful for quick calculations and data inspection.
def do_eval(state, args):
"""
Evaluate Python expression and print result.
Parameters:
- state: State object with active transport
- args: Arguments containing expression to evaluate
Args attributes:
- expr: List containing expression string to evaluate
"""Run local Python script files on MicroPython devices with output streaming and error reporting.
def do_run(state, args):
"""
Run local Python script on device.
Parameters:
- state: State object with active transport
- args: Arguments containing script path and options
Args attributes:
- path: List containing path to local script file
- follow: Boolean to follow output until completion (default True)
"""Internal function for executing code buffers with output control and streaming.
def _do_execbuffer(state, buf, follow):
"""
Execute code buffer on device.
Parameters:
- state: State object with transport
- buf: Bytes buffer containing code to execute
- follow: Whether to follow output until completion
Internal function used by exec, eval, and run commands.
"""# Execute Python statements
mpremote exec "print('Hello MicroPython!')"
mpremote exec "import os; print(os.listdir())"
# Execute multi-line code
mpremote exec "
for i in range(5):
print(f'Count: {i}')
"
# Execute without following output
mpremote exec --no-follow "import time; time.sleep(10)"# Evaluate expressions
mpremote eval "2 + 2"
mpremote eval "len(os.listdir())"
mpremote eval "micropython.mem_info()"
# Chain multiple evaluations
mpremote eval "1 + 1" eval "2 * 3" eval "4 ** 2"# Run local Python scripts
mpremote run main.py
mpremote run --follow sensor_test.py
mpremote run --no-follow background_task.py
# Run scripts with mounted directories
mpremote mount . run local_script.pyfrom mpremote.main import State
from mpremote.commands import do_exec, do_eval, do_run
# Set up connected device state
state = State()
# ... connect to device ...
# Execute basic code
args = type('Args', (), {
'expr': ['print("Hello from device!")'],
'follow': True
})()
do_exec(state, args)
# Evaluate expression
args = type('Args', (), {
'expr': ['micropython.mem_info()']
})()
do_eval(state, args)
# Run local script
args = type('Args', (), {
'path': ['sensor_reading.py'],
'follow': True
})()
do_run(state, args)# Memory information
mpremote eval "micropython.mem_info()"
# System details
mpremote exec "
import sys
print('Python version:', sys.version)
print('Platform:', sys.platform)
print('Implementation:', sys.implementation)
"
# Available modules
mpremote exec "
import sys
print('Available modules:')
for module in sorted(sys.modules.keys()):
print(' ', module)
"# GPIO control
mpremote exec "
from machine import Pin
led = Pin(2, Pin.OUT)
led.on()
"
# Sensor reading
mpremote exec "
from machine import ADC
adc = ADC(0)
reading = adc.read()
print(f'ADC reading: {reading}')
"
# I2C scan
mpremote exec "
from machine import Pin, I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
devices = i2c.scan()
print('I2C devices:', [hex(x) for x in devices])
"# Rapid prototyping cycle
mpremote exec "
# Test code directly on device
def test_function():
return 'Working!'
result = test_function()
print(result)
"
# Load and test modules
mpremote mount . exec "
import my_module
result = my_module.test_function()
print('Test result:', result)
"
# Performance testing
mpremote exec "
import time
start = time.ticks_ms()
# ... code to time ...
end = time.ticks_ms()
print(f'Execution time: {end - start} ms')
"When follow=True (default), mpremote streams output in real-time:
# This will show output as it's generated
mpremote exec "
import time
for i in range(10):
print(f'Progress: {i}/10')
time.sleep(0.5)
"When follow=False, execution returns immediately:
# This returns immediately, useful for starting background tasks
mpremote exec --no-follow "
import _thread
def background_task():
# Long running task
pass
_thread.start_new_thread(background_task, ())
"Code execution may encounter various error conditions:
from mpremote.transport import TransportExecError
try:
do_exec(state, args)
except TransportExecError as e:
print(f"Execution failed with status {e.status_code}")
print(f"Error output: {e.error_output}")
# Common error patterns
if "NameError" in e.error_output:
print("Undefined variable or function")
elif "SyntaxError" in e.error_output:
print("Invalid Python syntax")
elif "ImportError" in e.error_output:
print("Module not found")
elif "OSError" in e.error_output:
print("System or hardware error")# Break complex code into manageable pieces
mpremote exec "import machine; led = machine.Pin(2, machine.Pin.OUT)"
mpremote exec "led.on()"
mpremote exec "led.off()"
# Use meaningful variable names
mpremote exec "sensor_pin = machine.ADC(0)"
mpremote exec "reading = sensor_pin.read()"# Clean up resources
mpremote exec "
import gc
# ... do work ...
gc.collect() # Force garbage collection
"
# Check memory usage
mpremote eval "micropython.mem_info()"# Graceful error handling in device code
mpremote exec "
try:
# risky operation
result = risky_function()
print('Success:', result)
except Exception as e:
print('Error:', e)
# recovery actions
"Install with Tessl CLI
npx tessl i tessl/pypi-mpremote