vfs_userfs.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # test VFS functionality with a user-defined filesystem
  2. # also tests parts of uio.IOBase implementation
  3. import sys
  4. try:
  5. import uio
  6. uio.IOBase
  7. import uos
  8. uos.mount
  9. except (ImportError, AttributeError):
  10. print("SKIP")
  11. raise SystemExit
  12. class UserFile(uio.IOBase):
  13. def __init__(self, data):
  14. self.data = data
  15. self.pos = 0
  16. def read(self):
  17. return self.data
  18. def readinto(self, buf):
  19. n = 0
  20. while n < len(buf) and self.pos < len(self.data):
  21. buf[n] = self.data[self.pos]
  22. n += 1
  23. self.pos += 1
  24. return n
  25. def ioctl(self, req, arg):
  26. print('ioctl', req, arg)
  27. return 0
  28. class UserFS:
  29. def __init__(self, files):
  30. self.files = files
  31. def mount(self, readonly, mksfs):
  32. pass
  33. def umount(self):
  34. pass
  35. def stat(self, path):
  36. print('stat', path)
  37. if path in self.files:
  38. return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0)
  39. raise OSError
  40. def open(self, path, mode):
  41. print('open', path, mode)
  42. return UserFile(self.files[path])
  43. # create and mount a user filesystem
  44. user_files = {
  45. '/data.txt': b"some data in a text file\n",
  46. '/usermod1.py': b"print('in usermod1')\nimport usermod2",
  47. '/usermod2.py': b"print('in usermod2')",
  48. }
  49. uos.mount(UserFS(user_files), '/userfs')
  50. # open and read a file
  51. f = open('/userfs/data.txt')
  52. print(f.read())
  53. # import files from the user filesystem
  54. sys.path.append('/userfs')
  55. import usermod1
  56. # unmount and undo path addition
  57. uos.umount('/userfs')
  58. sys.path.pop()