CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mpremote

Tool for interacting remotely with MicroPython devices

Pending
Overview
Eval results
Files

code-execution.mddocs/

Code Execution

Execute Python code on MicroPython devices with support for expressions, multi-line statements, and local script execution with real-time output streaming.

Capabilities

Code Execution

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)
    """

Expression Evaluation

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
    """

Script Execution

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 Execution Buffer

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.
    """

Command-Line Interface

Basic Code Execution

# 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)"

Expression Evaluation

# 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"

Script Execution

# 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.py

Usage Examples

Interactive Development

from 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)

System Information Gathering

# 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)
"

Hardware Interaction

# 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])
"

Development Workflows

# 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')
"

Output Handling

Following Output

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)
"

Non-Following Execution

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, ())
"

Error Handling

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")

Best Practices

Code Organization

# 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()"

Resource Management

# Clean up resources
mpremote exec "
import gc
# ... do work ...
gc.collect()  # Force garbage collection
"

# Check memory usage
mpremote eval "micropython.mem_info()"

Error Recovery

# 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

docs

cli-reference.md

code-execution.md

device-config.md

device-connection.md

filesystem.md

index.md

mounting.md

package-management.md

repl.md

romfs.md

tile.json