When you issue pydb myscript.py
you are running pydb
first which then invokes your script myscript.py
. The debugger,
pydb
, tries hard to make itself transparent and thus strips its
own program options, resets sys.argv
and sets __file__
to the values you would get by calling the debugged program directly.
However there are times when this doesn't work right. It's probable that this method can't be made to work all the time, even though it works often enough.
So another approach which doesn't have this complexity or drawback is
to add a call to the debugger at special places. For this, the
pydb
function set_trace()
can be used. I've even this
method to debug the debugger itself and to debug regression tests.
When the pydb.set_trace()
function is called, the program stops
before the next statement. To continue running the program, issue a
debugger next
, step
or a continue
command.
The exit the program use the quit
or a termanal EOF.
To make this more clear, let's give go through an example. Save this
in a file called hardtodebug.py
:
import pydb # some code here def test(): # Force a call to the debugger in running code here pydb.set_trace() # ... # ... test() x=5
Now here's a sample run of the program:
python hardtodebug.py a b c --Return-- --Return-- (/home/src/external-cvs/pydb/Doc/lib/hardtodebug.py:9): (Pydb) list 4 # Force a call to the debugger in running code here 5 pydb.set_trace() 6 # ... 7 # ... 8 test() 9 -> x=5 (/home/src/external-cvs/pydb/Doc/lib/hardtodebug.py:9): (Pydb) restart Re exec'ing ['pydb', 'hardtodebug.py', 'a', 'b', 'c'] (/home/src/external-cvs/pydb/Doc/lib/hardtodebug.py:1): (Pydb)
The first --Return--
line printed is a result of the
set_trace()
exiting. But note that we stopped after the
return from test()
, which explains the second
--Return--
line. Because the next executable statement is after
the implicit return. If you want to stop inside test()
put a
statement after the set_trace()
, such as a return
statement. Furthermore, if the program had ended at line 8, then
no stopping would have occured becuase the end of the program
is reached first.1.2
Also note that we can issue a restart
which involves some
hackery. But at least in this case it gets things right.
set_trace
above. This
is not hard to code and I've done so, but I'm not sure that doesn't
just confuse things more.