From b3b9b11596b5b4c9a3c45185fd839fa3db63fa12 Mon Sep 17 00:00:00 2001 From: Damien George Date: Wed, 11 Dec 2019 14:56:33 +1100 Subject: [PATCH] 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 --- tools/pyboard.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tools/pyboard.py b/tools/pyboard.py index c32fb002c..2a255e91c 100755 --- a/tools/pyboard.py +++ b/tools/pyboard.py @@ -484,6 +484,33 @@ def filesystem_command(pyb, args): pyb.close() sys.exit(1) +_injected_import_hook_code = """\ +import uos, uio +class _FS: + class File(uio.IOBase): + def __init__(self): + self.off = 0 + def ioctl(self, request, arg): + return 0 + def readinto(self, buf): + buf[:] = memoryview(_injected_buf)[self.off:self.off + len(buf)] + self.off += len(buf) + return len(buf) + mount = umount = chdir = lambda *args: None + def stat(self, path): + if path == '_injected.mpy': + return tuple(0 for _ in range(10)) + else: + raise OSError(-2) # ENOENT + def open(self, path, mode): + return self.File() +uos.mount(_FS(), '/_') +uos.chdir('/_') +from _injected import * +uos.umount('/_') +del _injected_buf, _FS +""" + def main(): import argparse cmd_parser = argparse.ArgumentParser(description='Run scripts on the pyboard.') @@ -544,6 +571,9 @@ def main(): for filename in args.files: with open(filename, 'rb') as f: pyfile = f.read() + if filename.endswith('.mpy') and pyfile[0] == ord('M'): + pyb.exec_('_injected_buf=' + repr(pyfile)) + pyfile = _injected_import_hook_code execbuffer(pyfile) # exiting raw-REPL just drops to friendly-REPL mode