Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8609

MicroPython • Create a list of executable code

$
0
0
I am wanting to create a list of lines of executable MicroPython code so I can execute any item in that list in any order. I have managed to do it by turning each item into a function and having a list of functions I can call ...

Code:

SourceCode = """  print("  hello")              # 0  print("  says")               # 1  print("  world")              # 2"""Executable = []for s in SourceCode.split("\n"):  s = s.strip()  if s != "" and not s.startswith("#"):    exec("def DUMMY():" + s)    Executable.append(DUMMY)print("FORWARD")for n in range(len(Executable)):   Executable[n]()print("BACKWARD")for n in range(len(Executable) - 1, -1, -1):  Executable[n]()

Code:

FORWARD  hello  says  worldBACKWARD  world  says  hello
This works with Python 3, MicroPython, even when converted to a '.mpy' module for import.

Can anyone think of a better way to do it ?

There may be all kinds of tricks I don't know about involving disassembly and introspection which work with Desktop Python but, if they don't work for MicroPython, I can't use those.

Statistics: Posted by hippy — Wed Apr 02, 2025 11:51 pm



Viewing all articles
Browse latest Browse all 8609

Trending Articles