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
Coronavirus and Machine Learning Conferences
4 years ago
I'm a long-time Matlab user, just converting to Python.
ReplyDeleteThis 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.
My world just became a happier place.
ReplyDeleteOr better still, use ipython, and call:
ReplyDeletefrom IPython.Debugger import Tracer; debug_here = Tracer()
then you can just use
debug_here()
whenever you want to set a breakpoint
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.
ReplyDeleteA 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/):
ReplyDeleteIs 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.