1.3.1 Calling the Debugger from Inside your Program

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.



Footnotes

... first.1.2
Perhaps this is a deficiency of the debugger. I'm not sure what the right way to address though. One could have another routine to stop at a return which would then skip intervening statements. Another possibility is to add a routine to have debugger stop inside the call, e.g. 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.
See About this document... for information on suggesting changes.