Skip to content

Commit b3b9b11

Browse files
committed
tools/pyboard.py: Support executing .mpy files directly.
This patch allows executing .mpy files (including native ones) directly on a target, eg a board over a serial connection. So there's no need to copy the file to its filesystem to test it. For example: $ mpy-cross foo.py $ pyboard.py foo.mpy
1 parent 43b576d commit b3b9b11

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

tools/pyboard.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,33 @@ def fname_cp_dest(src, dest):
484484
pyb.close()
485485
sys.exit(1)
486486

487+
_injected_import_hook_code = """\
488+
import uos, uio
489+
class _FS:
490+
class File(uio.IOBase):
491+
def __init__(self):
492+
self.off = 0
493+
def ioctl(self, request, arg):
494+
return 0
495+
def readinto(self, buf):
496+
buf[:] = memoryview(_injected_buf)[self.off:self.off + len(buf)]
497+
self.off += len(buf)
498+
return len(buf)
499+
mount = umount = chdir = lambda *args: None
500+
def stat(self, path):
501+
if path == '_injected.mpy':
502+
return tuple(0 for _ in range(10))
503+
else:
504+
raise OSError(-2) # ENOENT
505+
def open(self, path, mode):
506+
return self.File()
507+
uos.mount(_FS(), '/_')
508+
uos.chdir('/_')
509+
from _injected import *
510+
uos.umount('/_')
511+
del _injected_buf, _FS
512+
"""
513+
487514
def main():
488515
import argparse
489516
cmd_parser = argparse.ArgumentParser(description='Run scripts on the pyboard.')
@@ -544,6 +571,9 @@ def execbuffer(buf):
544571
for filename in args.files:
545572
with open(filename, 'rb') as f:
546573
pyfile = f.read()
574+
if filename.endswith('.mpy') and pyfile[0] == ord('M'):
575+
pyb.exec_('_injected_buf=' + repr(pyfile))
576+
pyfile = _injected_import_hook_code
547577
execbuffer(pyfile)
548578

549579
# exiting raw-REPL just drops to friendly-REPL mode

0 commit comments

Comments
 (0)