I want to write Python code that can execute other Python code line by line, but without user interaction as with pdb. I want essentially exec()
, but one line at a time.
For example, I would like to write code such as this:
import non_interactive_pdb as ni_pdb
def interleave(code1, code2):
'''"Interleave" the execution of code1 and code2, which are two strings
representing Python source code, by alternately running one line
from code1 and followed by one line from code2.'''
prog1 = ni_pdb.compile(code1)
prog2 = ni_pdb.compile(code2)
while not prog1.terminated() and not prog2.terminated():
prog1.exec_next_line()
prog2.exec_next_line()
if prog1.terminated():
while not prog2.terminated():
prog2.exec_next_line()
if prog2.terminated():
while not prog1.terminated():
prog1.exec_next_line()
This is just an example. I'm sure there is a more efficient way to have the same effect as the above code --- e.g., exec(code1); exec(code2)
--- but that's not what I'm after.