Skip to content

Sample MicroPython OS functions

MicroPython provides a small list of os functions that allow you to manipulate files on the local filesystem of a MicroController.

These functions for filesystem access, and mounting, terminal redirection and duplication, and the uname and urandom functions.

These commands include:

  • uname - get system information such as the release of the runtime and machine type
  • listdir - list directory
  • ilistdir - list all files including low-level i-node statistics
  • getcwd - get current working directory
  • chdir - change directory
  • mkdir -
  • mount/umount - mount or unmount a remote directory as a local file system
  • remove - remove a file
  • stat - get statistics about a file or directory
  • rmdir - remove a directory

UName: Getting System Information

1
2
3
import os
uname = os.uname()
print(uname)

Returns:

1
2
3
4
5
6
7
(
   sysname='rp2',
   nodename='rp2',
   release='1.19.1',
   version='v1.19.1-88-g74e33e714 on 2022-06-30 (GNU 11.2.0 MinSizeRel)',
   machine='Raspberry Pi Pico W with RP2040'
)

Thonny does not easily allow you to delete files. To do this you will need to use the "os" functions.

1
2
3
4
import os
os.listdir()
os.remove('myfile')
os.listdir()

To find out all the os functions use:

1
2
3
4
5
import os
print(dir(os))
``

Returns
['class', 'name', 'remove', 'VfsFat', 'VfsLfs2', 'chdir', 'getcwd', 'ilistdir', 'listdir', 'mkdir', 'mount', 'rename', 'rmdir', 'stat', 'statvfs', 'umount', 'uname', 'urandom']`

Percent Storage Full and Free RAM

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import gc
import os

def df():
  s = os.statvfs('//')
  return ('{0} MB'.format((s[0]*s[3])/1048576))

def free(full=False):
  F = gc.mem_free()
  A = gc.mem_alloc()
  T = F+A
  P = '{0:.2f}%'.format(F/T*100)
  if not full: return P
  else : return ('Total:{0} Free:{1} ({2})'.format(T,F,P))

def free-gc(full=False):
  gc.collect()
  F = gc.mem_free()
  A = gc.mem_alloc()
  T = F+A
  P = '{0:.2f}%'.format(F/T*100)
  if not full: return P
  else : return ('Total:{0} Free:{1} ({2})'.format(T,F,P))

print(df())

print(free())

print(free-gc())

Machine Clock frequency

1
print('Machine Clock Frequency:', '{:,} MHz'.format(machine.freq()/1000000))

returns:

1
Machine Clock Frequency: 125 MHz

References

https://www.youtube.com/watch?v=jnSX8ZMmHZ4