0
# Code Execution
1
2
Execute Python code on MicroPython devices with support for expressions, multi-line statements, and local script execution with real-time output streaming.
3
4
## Capabilities
5
6
### Code Execution
7
8
Execute Python code strings on MicroPython devices with optional output following and error handling.
9
10
```python { .api }
11
def do_exec(state, args):
12
"""
13
Execute Python code string on device.
14
15
Parameters:
16
- state: State object with active transport
17
- args: Arguments containing code expression and options
18
19
Args attributes:
20
- expr: List containing code string to execute
21
- follow: Boolean to follow output until completion (default True)
22
"""
23
```
24
25
### Expression Evaluation
26
27
Evaluate Python expressions and print the result, useful for quick calculations and data inspection.
28
29
```python { .api }
30
def do_eval(state, args):
31
"""
32
Evaluate Python expression and print result.
33
34
Parameters:
35
- state: State object with active transport
36
- args: Arguments containing expression to evaluate
37
38
Args attributes:
39
- expr: List containing expression string to evaluate
40
"""
41
```
42
43
### Script Execution
44
45
Run local Python script files on MicroPython devices with output streaming and error reporting.
46
47
```python { .api }
48
def do_run(state, args):
49
"""
50
Run local Python script on device.
51
52
Parameters:
53
- state: State object with active transport
54
- args: Arguments containing script path and options
55
56
Args attributes:
57
- path: List containing path to local script file
58
- follow: Boolean to follow output until completion (default True)
59
"""
60
```
61
62
### Internal Execution Buffer
63
64
Internal function for executing code buffers with output control and streaming.
65
66
```python { .api }
67
def _do_execbuffer(state, buf, follow):
68
"""
69
Execute code buffer on device.
70
71
Parameters:
72
- state: State object with transport
73
- buf: Bytes buffer containing code to execute
74
- follow: Whether to follow output until completion
75
76
Internal function used by exec, eval, and run commands.
77
"""
78
```
79
80
## Command-Line Interface
81
82
### Basic Code Execution
83
84
```bash
85
# Execute Python statements
86
mpremote exec "print('Hello MicroPython!')"
87
mpremote exec "import os; print(os.listdir())"
88
89
# Execute multi-line code
90
mpremote exec "
91
for i in range(5):
92
print(f'Count: {i}')
93
"
94
95
# Execute without following output
96
mpremote exec --no-follow "import time; time.sleep(10)"
97
```
98
99
### Expression Evaluation
100
101
```bash
102
# Evaluate expressions
103
mpremote eval "2 + 2"
104
mpremote eval "len(os.listdir())"
105
mpremote eval "micropython.mem_info()"
106
107
# Chain multiple evaluations
108
mpremote eval "1 + 1" eval "2 * 3" eval "4 ** 2"
109
```
110
111
### Script Execution
112
113
```bash
114
# Run local Python scripts
115
mpremote run main.py
116
mpremote run --follow sensor_test.py
117
mpremote run --no-follow background_task.py
118
119
# Run scripts with mounted directories
120
mpremote mount . run local_script.py
121
```
122
123
## Usage Examples
124
125
### Interactive Development
126
127
```python
128
from mpremote.main import State
129
from mpremote.commands import do_exec, do_eval, do_run
130
131
# Set up connected device state
132
state = State()
133
# ... connect to device ...
134
135
# Execute basic code
136
args = type('Args', (), {
137
'expr': ['print("Hello from device!")'],
138
'follow': True
139
})()
140
do_exec(state, args)
141
142
# Evaluate expression
143
args = type('Args', (), {
144
'expr': ['micropython.mem_info()']
145
})()
146
do_eval(state, args)
147
148
# Run local script
149
args = type('Args', (), {
150
'path': ['sensor_reading.py'],
151
'follow': True
152
})()
153
do_run(state, args)
154
```
155
156
### System Information Gathering
157
158
```bash
159
# Memory information
160
mpremote eval "micropython.mem_info()"
161
162
# System details
163
mpremote exec "
164
import sys
165
print('Python version:', sys.version)
166
print('Platform:', sys.platform)
167
print('Implementation:', sys.implementation)
168
"
169
170
# Available modules
171
mpremote exec "
172
import sys
173
print('Available modules:')
174
for module in sorted(sys.modules.keys()):
175
print(' ', module)
176
"
177
```
178
179
### Hardware Interaction
180
181
```bash
182
# GPIO control
183
mpremote exec "
184
from machine import Pin
185
led = Pin(2, Pin.OUT)
186
led.on()
187
"
188
189
# Sensor reading
190
mpremote exec "
191
from machine import ADC
192
adc = ADC(0)
193
reading = adc.read()
194
print(f'ADC reading: {reading}')
195
"
196
197
# I2C scan
198
mpremote exec "
199
from machine import Pin, I2C
200
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
201
devices = i2c.scan()
202
print('I2C devices:', [hex(x) for x in devices])
203
"
204
```
205
206
### Development Workflows
207
208
```bash
209
# Rapid prototyping cycle
210
mpremote exec "
211
# Test code directly on device
212
def test_function():
213
return 'Working!'
214
215
result = test_function()
216
print(result)
217
"
218
219
# Load and test modules
220
mpremote mount . exec "
221
import my_module
222
result = my_module.test_function()
223
print('Test result:', result)
224
"
225
226
# Performance testing
227
mpremote exec "
228
import time
229
start = time.ticks_ms()
230
# ... code to time ...
231
end = time.ticks_ms()
232
print(f'Execution time: {end - start} ms')
233
"
234
```
235
236
## Output Handling
237
238
### Following Output
239
240
When `follow=True` (default), mpremote streams output in real-time:
241
242
```bash
243
# This will show output as it's generated
244
mpremote exec "
245
import time
246
for i in range(10):
247
print(f'Progress: {i}/10')
248
time.sleep(0.5)
249
"
250
```
251
252
### Non-Following Execution
253
254
When `follow=False`, execution returns immediately:
255
256
```bash
257
# This returns immediately, useful for starting background tasks
258
mpremote exec --no-follow "
259
import _thread
260
def background_task():
261
# Long running task
262
pass
263
_thread.start_new_thread(background_task, ())
264
"
265
```
266
267
## Error Handling
268
269
Code execution may encounter various error conditions:
270
271
```python
272
from mpremote.transport import TransportExecError
273
274
try:
275
do_exec(state, args)
276
except TransportExecError as e:
277
print(f"Execution failed with status {e.status_code}")
278
print(f"Error output: {e.error_output}")
279
280
# Common error patterns
281
if "NameError" in e.error_output:
282
print("Undefined variable or function")
283
elif "SyntaxError" in e.error_output:
284
print("Invalid Python syntax")
285
elif "ImportError" in e.error_output:
286
print("Module not found")
287
elif "OSError" in e.error_output:
288
print("System or hardware error")
289
```
290
291
## Best Practices
292
293
### Code Organization
294
295
```bash
296
# Break complex code into manageable pieces
297
mpremote exec "import machine; led = machine.Pin(2, machine.Pin.OUT)"
298
mpremote exec "led.on()"
299
mpremote exec "led.off()"
300
301
# Use meaningful variable names
302
mpremote exec "sensor_pin = machine.ADC(0)"
303
mpremote exec "reading = sensor_pin.read()"
304
```
305
306
### Resource Management
307
308
```bash
309
# Clean up resources
310
mpremote exec "
311
import gc
312
# ... do work ...
313
gc.collect() # Force garbage collection
314
"
315
316
# Check memory usage
317
mpremote eval "micropython.mem_info()"
318
```
319
320
### Error Recovery
321
322
```bash
323
# Graceful error handling in device code
324
mpremote exec "
325
try:
326
# risky operation
327
result = risky_function()
328
print('Success:', result)
329
except Exception as e:
330
print('Error:', e)
331
# recovery actions
332
"
333
```