xralf
xralf

Reputation: 3742

Debugging code in the Python interpreter

I like testing functions in the Python interpreter. Is it possible to debug a function in the Python interpreter when I want to see more than a return value and a side effect?

If so, could you show basic debugger operations (launching the function with arguments, setting breakpoint, next step, step into, watching variable)? If not, how would you debug a function another way?

The point is, I want to debug only a particular function which will be supplied with arguments. I don't want to debug whole module code.

thank you for advice

Upvotes: 16

Views: 10076

Answers (3)

gunderbolt
gunderbolt

Reputation: 163

The code-to-debug does not need to be modified to include pdb.set_trace(). That call can be made directly in the interpreter just before the code-to-debug:

>>> import pdb
>>> pdb.set_trace(); <code-to-debug>

For example, given test_script.py with the following code:

def some_func(text):
    print 'Given text is {}'.format(repr(text))
    for index,char in enumerate(text):
        print ' '*index, char

an interpreter session to debug some_func using the debugger commands step-into (s), next (n) and continue (c) would look like:

>>> import pdb
>>> import test_script
>>> pdb.set_trace(); test_script.some_func('hello')
--Call--
> c:\src\test_script.py(1)some_func()
-> def some_func(text):
(Pdb) s
> c:\src\test_script.py(2)some_func()
-> print 'Given text is {}'.format(repr(text))
(Pdb) n
Given text is 'hello'
> c:\src\test_script.py(3)some_func()
-> for index,char in enumerate(text):
(Pdb) c
 h
  e
   l
    l
     o
>>> 

See the docs for the pdb module for more information on how to use the debugger: http://docs.python.org/library/pdb.html

Additionally, while using the debugger, the help command provides a nice list of commands and help <command> gives help specific to the given command.

Upvotes: 5

Karthik Ananth
Karthik Ananth

Reputation: 211

If you want to debug specific function you can using this -

>>> import pdb
>>> import yourmodule
>>> pdb.run('yourmodule.foo()')

over the command line. pdb.set_trace() should be added in your function to break there.

More info on pdb can be seen here - http://docs.python.org/library/pdb.html

Upvotes: 12

Bittrance
Bittrance

Reputation: 2260

See pdb module. Insert into code:

import pdb
pdb.set_trace()

... makes a breakpoint.

Upvotes: 7

Related Questions