0

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.

Dave Doty
  • 285
  • 1
  • 9
  • 1
    Do you mean one statement at a time, rather than one line at a time? Do you want to step into function calls? – Peter Wood Jun 07 '16 at 19:50
  • Do they run in the same namespace? Can they affect each other? – Alex Hall Jun 07 '16 at 20:00
  • Yes, one statement at a time. And yes, I would like it to step into function calls. The idea is that as long as the statement is "basic enough" (e.g., simple assignment statements, comparisons, etc.), there's no chance of it entering an infinite loop and not returning from exec_next_line. Just like a debugger, only without a person needing to press buttons or keys to run it. – Dave Doty Jun 07 '16 at 20:01
  • 1
    Use bdb to write your own 'debugger'. It's the base class of pdb. – Alex Hall Jun 07 '16 at 20:02
  • What are you trying to achieve? There are probably better ways, eg. threads, multiprocessing, using yield, etc. – Peter Wood Jun 08 '16 at 04:51
  • Hi Peter: I'm trying to achieve exactly the behavior above. It's because I want to use Python to teach certain concepts in theoretical computer science that involve doing things such as the above, e.g., "run program p1 for one step, then run programs p1 and p2 for one step each, then run programs p1, p2, p3 for one step each, ..." This is possible in principle to do in any language, but I am looking for a concrete, *simple* way to do it in Python. The key is that this sort of trick is used when you don't know in advance which programs halt so you can't just say "run it". – Dave Doty Jun 08 '16 at 21:50

0 Answers0