0
# Filesystem Operations
1
2
Comprehensive filesystem operations for managing files and directories on MicroPython devices, including file transfer, directory manipulation, and content inspection.
3
4
## Capabilities
5
6
### Main Filesystem Command Dispatcher
7
8
Central dispatcher for all filesystem operations with support for various commands and options.
9
10
```python { .api }
11
def do_filesystem(state, args):
12
"""
13
Execute filesystem commands on the device.
14
15
Parameters:
16
- state: State object with active transport
17
- args: Arguments containing command and paths
18
19
Supported commands: cat, ls, cp, rm, mkdir, rmdir, sha256sum, touch, tree
20
"""
21
```
22
23
### File Copy Operations
24
25
Copy files and directories between local filesystem and MicroPython device with progress indication and hash verification.
26
27
```python { .api }
28
def do_filesystem_cp(state, src, dest, multiple, check_hash=False):
29
"""
30
Copy files between local and remote filesystems.
31
32
Parameters:
33
- state: State object with transport
34
- src: Source file/directory path
35
- dest: Destination path
36
- multiple: Whether copying multiple files
37
- check_hash: Verify file integrity with SHA256
38
39
Path prefixes:
40
- ":" prefix indicates remote device path
41
- No prefix indicates local filesystem path
42
"""
43
44
def do_filesystem_recursive_cp(state, src, dest, multiple, check_hash):
45
"""
46
Recursively copy directories with all contents.
47
48
Parameters:
49
- state: State object with transport
50
- src: Source directory path
51
- dest: Destination directory path
52
- multiple: Multiple file operation flag
53
- check_hash: Hash verification flag
54
"""
55
```
56
57
### File and Directory Management
58
59
Create, remove, and manage files and directories on the device filesystem.
60
61
```python { .api }
62
def do_filesystem_recursive_rm(state, path, args):
63
"""
64
Recursively remove directories and contents.
65
66
Parameters:
67
- state: State object with transport
68
- path: Directory path to remove
69
- args: Command arguments with options
70
"""
71
```
72
73
### Directory Tree Display
74
75
Display directory structure in tree format with optional file sizes and human-readable formatting.
76
77
```python { .api }
78
def do_filesystem_tree(state, path, args):
79
"""
80
Display directory tree structure.
81
82
Parameters:
83
- state: State object with transport
84
- path: Root path for tree display
85
- args: Display options (size, human-readable)
86
"""
87
```
88
89
### File Editing
90
91
Edit files on the device using the system's default editor with automatic download/upload.
92
93
```python { .api }
94
def do_edit(state, args):
95
"""
96
Edit files on the device using system editor.
97
98
Parameters:
99
- state: State object with active transport
100
- args: Arguments containing file paths to edit
101
102
Args attributes:
103
- files: List of remote file paths to edit (use : prefix)
104
105
Downloads files to temporary location, opens in $EDITOR,
106
and uploads changes back to device on save.
107
"""
108
```
109
110
### Utility Functions
111
112
Helper functions for filesystem operations and user feedback.
113
114
```python { .api }
115
def show_progress_bar(size, total_size, op="copying"):
116
"""
117
Display progress bar for file operations.
118
119
Parameters:
120
- size: Current bytes transferred
121
- total_size: Total bytes to transfer
122
- op: Operation description
123
"""
124
125
def human_size(size, decimals=1):
126
"""
127
Format file size in human-readable format.
128
129
Parameters:
130
- size: Size in bytes
131
- decimals: Decimal places for formatting
132
133
Returns:
134
- str: Formatted size (e.g., "1.5 MB", "256 KB")
135
"""
136
```
137
138
### Path Utilities
139
140
Remote path manipulation utilities for device filesystem operations.
141
142
```python { .api }
143
def _remote_path_join(a, *b):
144
"""
145
Join remote filesystem paths.
146
147
Parameters:
148
- a: Base path
149
- b: Additional path components
150
151
Returns:
152
- str: Joined path using forward slashes
153
"""
154
155
def _remote_path_dirname(a):
156
"""
157
Get directory name of remote path.
158
159
Parameters:
160
- a: Path string
161
162
Returns:
163
- str: Directory portion of path
164
"""
165
166
def _remote_path_basename(a):
167
"""
168
Get base name of remote path.
169
170
Parameters:
171
- a: Path string
172
173
Returns:
174
- str: Base filename
175
"""
176
```
177
178
## Command-Line Interface
179
180
### File Operations
181
182
```bash
183
# List directory contents
184
mpremote ls
185
mpremote ls :lib # list remote directory
186
mpremote fs ls -l # detailed listing
187
188
# Display file contents
189
mpremote cat :main.py
190
mpremote fs cat boot.py
191
192
# Copy files
193
mpremote cp main.py : # local to device
194
mpremote cp :main.py . # device to local
195
mpremote cp -r src/ : # recursive copy
196
mpremote cp -f main.py :main.py # force overwrite
197
198
# File operations
199
mpremote rm :old_file.py
200
mpremote mkdir :new_dir
201
mpremote rmdir :empty_dir
202
mpremote touch :new_file.py
203
204
# Edit files on device
205
mpremote edit :main.py # Edit single file
206
mpremote edit :boot.py :main.py # Edit multiple files
207
```
208
209
### Directory Operations
210
211
```bash
212
# Recursive operations
213
mpremote rm -r :old_directory
214
mpremote cp -r local_dir/ :remote_dir/
215
216
# Directory tree display
217
mpremote tree
218
mpremote fs tree :lib
219
mpremote fs tree -s :lib # show sizes
220
mpremote fs tree -h :lib # human-readable sizes
221
```
222
223
### File Verification
224
225
```bash
226
# Calculate file hashes
227
mpremote sha256sum :main.py
228
mpremote fs sha256sum boot.py main.py
229
230
# Show disk usage information
231
mpremote df
232
233
# Copy with hash verification
234
mpremote fs cp --force main.py :main.py # verifies by default
235
```
236
237
## Usage Examples
238
239
### Basic File Management
240
241
```python
242
from mpremote.main import State
243
from mpremote.commands import do_filesystem
244
245
# Set up state with connected device
246
state = State()
247
# ... connect to device ...
248
249
# List root directory
250
args = type('Args', (), {
251
'command': ['ls'],
252
'path': [':'],
253
'recursive': False,
254
'verbose': True
255
})()
256
do_filesystem(state, args)
257
258
# Copy local file to device
259
args = type('Args', (), {
260
'command': ['cp'],
261
'path': ['main.py', ':main.py'],
262
'recursive': False,
263
'force': False
264
})()
265
do_filesystem(state, args)
266
```
267
268
### Directory Tree Exploration
269
270
```python
271
# Display directory tree with sizes
272
args = type('Args', (), {
273
'command': ['tree'],
274
'path': [':'],
275
'size': True,
276
'human': False,
277
'verbose': True
278
})()
279
do_filesystem(state, args)
280
```
281
282
## Path Conventions
283
284
mpremote uses specific path conventions to distinguish between local and remote paths:
285
286
- **Remote paths**: Prefixed with `:` (e.g., `:main.py`, `:lib/module.py`)
287
- **Local paths**: No prefix (e.g., `main.py`, `src/module.py`)
288
- **Current directory**: `.` for local, `:` for remote root
289
290
## Error Handling
291
292
Filesystem operations may encounter various error conditions:
293
294
```python
295
from mpremote.transport import TransportError, TransportExecError
296
297
try:
298
do_filesystem(state, args)
299
except TransportExecError as e:
300
if "ENOENT" in e.error_output:
301
print("File or directory not found")
302
elif "EACCES" in e.error_output:
303
print("Permission denied")
304
elif "ENOSPC" in e.error_output:
305
print("No space left on device")
306
except TransportError as e:
307
print(f"Communication error: {e}")
308
```
309
310
## Supported Filesystem Commands
311
312
- **cat**: Display file contents
313
- **ls**: List directory contents with optional detailed format
314
- **cp**: Copy files/directories with recursive and force options
315
- **rm**: Remove files/directories with recursive option
316
- **mkdir**: Create directories
317
- **rmdir**: Remove empty directories
318
- **touch**: Create empty files or update timestamps
319
- **tree**: Display directory tree structure
320
- **sha256sum**: Calculate and verify file checksums