This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let\'s say an IndexError, pyth
Use the following module:
import sys
def info(type, value, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(type, value, tb)
else:
import traceback, pdb
# we are NOT in interactive mode, print the exception...
traceback.print_exception(type, value, tb)
print
# ...then start the debugger in post-mortem mode.
# pdb.pm() # deprecated
pdb.post_mortem(tb) # more "modern"
sys.excepthook = info
Name it debug
(or whatever you like) and put it somewhere in your python path.
Now, at the start of your script, just add an import debug
.
You can put this line in your code:
import pdb ; pdb.set_trace()
More info: Start the python debugger at any line
python -m pdb -c continue myscript.py
If you don't provide the -c continue
flag then you'll need to enter 'c' (for Continue) when execution begins. Then it will run to the error point and give you control there. As mentioned by eqzx, this flag is a new addition in python 3.2 so entering 'c' is required for earlier Python versions (see https://docs.python.org/3/library/pdb.html).
This isn't the debugger, but probably just as useful(?)
I know I heard Guido mention this in a speech somewhere.
I just checked python -?, and if you use the -i command you can interact where your script stopped.
So given this script:
testlist = [1,2,3,4,5, 0]
prev_i = None
for i in testlist:
if not prev_i:
prev_i = i
else:
result = prev_i/i
You can get this output!
PS D:\> python -i debugtest.py
Traceback (most recent call last):
File "debugtest.py", line 10, in <module>
result = prev_i/i
ZeroDivisionError: integer division or modulo by zero
>>>
>>>
>>> prev_i
1
>>> i
0
>>>
To be honest I haven't used this, but I should be, seems very useful.
python -m pdb script.py in python2.7 press continue to start and it will run to the error and break there for debug.
Ipython has a command for toggling this behavior: %pdb. It does exactly what you described, maybe even a bit more (giving you more informative backtraces with syntax highlighting and code completion). It's definitely worth a try!