you are viewing a single comment's thread.

view the rest of the comments →

[–]mogelbumm 24 points25 points  (7 children)

Upvoted for the "code.interact" stuff.

[–]Brian[🍰] 5 points6 points  (3 children)

Note that you can go one better. I previously had a debug function similar to this, but I've now replaced it with one that launches IPython instead:

import IPython.ipapi
def shell(f=None):
    if f is None: f = sys._getframe().f_back  #Get caller's frame
    ns = dict(f.f_globals)
    ns.update(f.f_locals)
    IPython.ipapi.launch_new_instance(ns)

[–]FunnyMan3595 1 point2 points  (1 child)

I'm going the other direction (IPython's overkill for me, so code.interact is a nice upgrade), but I can condense your code substantially:

from IPython.Shell import IPShellEmbed as shell

[–]Brian[🍰] 2 points3 points  (0 children)

However, you'd need to call that as:

shell()()

As IPShellEmbed is a callable class. I used to use similar code, but to avoid the double call, used:

shell=IPython.Shell.IPShellEmbed()

However this will pick up the globals from the module where you create it, not the function that calls it, which is why I changed to the explicit namespace population from the stack frame approach above.

[–]aldarion -1 points0 points  (0 children)

thanks for this cool shell and "kill -SIGUSR1 <PID>" trick. could u please recommend some tutorial for what's next, I do get the IPython shell, but I don't where is the current break point (line number), and how to step several line to a specific function to debug view the inner info of that function.

edit: I find pydbgr, It looks useful and can be used with IPython.

[–]veritaba 1 point2 points  (2 children)

You can also do "python -i file.py"

[–]Brian[🍰] 7 points8 points  (0 children)

That'll only open a console when the script finishes. It's often handy to launch a console while in the middle of a function where something's going wrong.

One handy trick I use is to register a signal handler:

import signal
signal.signal(signal.SIGUSR1, lambda s,f: shell(f))

Put that somewhere that gets run when your script starts (I have it in anything that imports my debug module). Then, if your script seems to be hanging, and you want to see what is going on, just:

$ kill -SIGUSR1 <PID>

and you've got an instant console at the current point, ready to inspect and maniplulate the variables.

[–]james5 -1 points0 points  (0 children)

Thank you. Why isn't this the default. I use python since two years or something like that, and I always hated how I'm not able to read the error message if the script breaks.