Reputation: 899
I am trying to find a way that I can have a program step through Python code line by line and do something with the results of each line. In effect a debugger that could be controlled programmatically rather than manually. pdb would be exactly what I am looking for if it returned its output after each step as a string and I could then call pdb again to pickup where I left off. However, instead it outputs to stdout and I have to manually input "step" via the keyboard.
Things I have tried:
I am able to redirect pdb's stdout. I could redirect it to a second Python program which would then process it. However, I cannot figure out how to have the second Python program tell pdb to step.
Related to the previous one, if I could get pdb to step all the way through to the end (perhaps I could figure out something to spoof a keyboard repeatedly entering "step"?) and redirect the output to a file, I could then write another program that acted like it was stepping through the program when it was actually just reading the file line by line.
I could use exec to manually run lines of Python code. However, since I would be looking at one line at a time, I would need to manually detect and handle things like conditionals, loops, and function calls which quickly gets very complicated.
I read some posts that say that pdb is implemented using sys.settrace. If nothing else works I should be able to recreate the behavior I need using this.
Is there any established/straight forward way to implement the behavior that I am looking for?
Upvotes: 3
Views: 1920
Reputation: 2458
I read some posts that say that pdb is implemented using sys.settrace. If nothing else works I should be able to recreate the behavior I need using this.
Don't view this as a last resort. I think it's the best approach for what you want to accomplish.
Upvotes: 1
Reputation: 9622
sys.settrace()
is the fundamental building block for stepping through Python code. pdb is implemented entirely in Python, so you can just look at the module to see how it does things. It also has various public functions/methods for stepping under program control, read the library reference for your version of Python for details.
Upvotes: 2