Friday, November 12, 2010

Matlab's keyboard command in python

A nice function to mimic matlab's keyboard command in python.

import code
import sys
def keyboard(banner=None):
    ''' Function that mimics the matlab keyboard command '''
    # use exception trick to pick up the current frame
    try:
        raise None
    except:
        frame = sys.exc_info()[2].tb_frame.f_back
    print "# Use quit() to exit :) Happy debugging!"
    # evaluate commands in current namespace
    namespace = frame.f_globals.copy()
    namespace.update(frame.f_locals)
    try:
        code.interact(banner=banner, local=namespace)
    except SystemExit:
        return 

5 comments:

  1. I'm a long-time Matlab user, just converting to Python.

    This command is great!!!

    However, it only seems to work from a shell prompt (that is, if you run your program as
    > python prog.py )

    It seems to get stuck in an infinite loop when using the ipython interactive shell.

    Is there a way to make this work with ipython?

    Thanks!!!

    Luis.

    ReplyDelete
  2. My world just became a happier place.

    ReplyDelete
  3. Or better still, use ipython, and call:

    from IPython.Debugger import Tracer; debug_here = Tracer()

    then you can just use

    debug_here()

    whenever you want to set a breakpoint

    ReplyDelete
  4. When using this function, I found that multiple calls to keyboard() within a single execution of a script resulted in a ValueError thrown form the code.interact() function. While I didn't find the exact source of this error, I noticed that if I exited the python interaction with ctrl-d instead of quit(), the error went away.

    ReplyDelete
  5. A bit late, but I've just come across this (from here http://nongeekrecipes.org/2013/02/16/is-there-a-python-equivalent-of-the-matlab-command-keyboard/):

    Is there a python equivalent of the matlab command keyboard?

    Sort of. Wherever you want to stop the execution of your code to have access to the python prompt (and to the current local variables) just insert the lines:

    import code
    code.interact(local=locals())

    To resume the execution press Ctrl-D.

    ReplyDelete