I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.
Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!
-
You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory.
-
http://docs.python.org/3.0/library/functions.html#input
http://docs.python.org/3.0/library/functions.html#evaldef start_interpreter(): while(True): code = input("Python Console >") eval(code)
I'm sure, however, that their implementation is much more foolsafe than this.
John Fouhy : Isn't input() equivalent to eval(raw_input()) ?nosklo : @John: not in python > 3.0 -
Python has a debugger framework in the bdb module. I'm not sure if the IDE's you list use it but it's certainly possible to implement a full Python debugger with it.
-
Right, I'm ashamed to admit it's actually in the documentation for InteractiveConsole after all. You can make it run in the local context by passing in the result of the locals() function to the InteractiveConsole constructor. I couldn't find a way to close the InteractiveConsole without killing the application, so I've extended it to just close the console when it catches the SystemExit exception. I don't like it, but I haven't yet found a better way.
Here's some (fairly trivial) sample code that demonstrates the debug console.
import code class EmbeddedConsole(code.InteractiveConsole): def start(self): try: self.interact("Debug console starting...") except: print("Debug console closing...") def print_names(): print(adam) print(bob) adam = "I am Adam" bob = "I am Bob" print_names() console = EmbeddedConsole(locals()) console.start() print_names()
-
If you want to experiment with your own Python console then this is a nice start:
cmd = None while cmd != 'exit': cmd = raw_input('>>> ') try: exec(cmd) except: print 'exception'
But for real work use the InteractiveConsole instead.
0 comments:
Post a Comment