Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way for interactive debug in python?

I want to utilize introspection capability of python for debugging/development, but cannot find appropriate tool for this.

I need to enter into shell (IPython for example) at specific position or at specific event (like exception), with locals and globals of shell being set to the frame's ones.

My own quick hack to illustrate it:

import inspect
from IPython.Shell import IPShellEmbed
def run_debug():
    stack = inspect.stack()
    frame = stack[1][0]
    loc = frame.f_locals
    glob = frame.f_globals
    shell = IPShellEmbed()
    shell(local_ns=loc, global_ns=glob)

With according run_debug() call from 'breakpoint' or try/except. But, obviously, this needs alot of polishing, esp to work with threaded apps properly.

winpdb has breakpoints with console, but I found no way to quickly run proper python shell from it, and eval()/exec() are not very handy for long debug.

like image 619
Daniel Kluev Avatar asked Jul 22 '10 14:07

Daniel Kluev


People also ask

Is Python good for debugging?

Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules.

Why PBD is better than just using print statements?

It is well-standardized and simple, as Python has a powerful logging framework in its standard library. Additionally, logging can be better than using print statements as you can not only get the log record, but also access events automatically logged in included modules.


2 Answers

Similar to what you're already doing, there's ipdb. Effectively, it's pdb with ipython's shell (i.e. tab completion, all the various magic functions, etc).

It's actually doing exactly what the little code snipped you posted in your question does, but wraps it into a simple "ipdb.set_trace()" call.

like image 200
Joe Kington Avatar answered Nov 04 '22 06:11

Joe Kington


For personal/education purposes you can use WingIDE - they have some pretty solid debugging capabilities.

Of course if you're just worried about changing values you can always just use raw_input() - but that may not be advanced enough for your needs.

like image 31
Wayne Werner Avatar answered Nov 04 '22 06:11

Wayne Werner