Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I start the python console within a program (for easy debugging)?

After years of research programming in Matlab, I miss the way I could pause a program mid-execution and inspect the variables, do plotting, save/modify data, etc. via the interactive console, and then resume execution.

Is there a way to do the same thing in python?

For example:


   # ... python code ...
   RunInterpreter
   # Interactive console is displayed, so user can inspect local/global variables
   # User types CTRL-D to exit, and script then continues to run
   # ... more python code ...

This would make debugging a lot easier. Suggestions much appreciated, thanks!

like image 718
Ciaran Avatar asked Dec 22 '10 17:12

Ciaran


3 Answers

Use the pdb library.

I have this line bound to <F8> in Vim:

import pdb; pdb.set_trace()

That will drop you into a pdb console.

The pdb console isn't quite the same as the standard Python console… But it will do most of the same stuff. Also, in my ~/.pdbrc, I've got:

alias i from IPython.Shell import IPShellEmbed as IPSh; IPSh(argv='')()

So that I can get into a "real" iPython shell from pdb with the i command:

(pdb) i
...
In [1]:
like image 198
David Wolever Avatar answered Sep 28 '22 00:09

David Wolever


The excellent solution I found was to use the 'code' module. I can now call 'DebugKeyboard()' from anywhere in my code and the interpreter prompt will pop-up, allowing me to examine variables and run code. CTRL-D will continue the program.

import code
import sys    

def DebugKeyboard(banner="Debugger started (CTRL-D to quit)"):

    # use exception trick to pick up the current frame
    try:
        raise None
    except:
        frame = sys.exc_info()[2].tb_frame.f_back

    # evaluate commands in current namespace
    namespace = frame.f_globals.copy()
    namespace.update(frame.f_locals)

    print "START DEBUG"
    code.interact(banner=banner, local=namespace)
    print "END DEBUG"
like image 27
Ciaran Avatar answered Sep 27 '22 22:09

Ciaran


The code module contains classes for bringing up a REPL.

like image 30
Ignacio Vazquez-Abrams Avatar answered Sep 27 '22 23:09

Ignacio Vazquez-Abrams