Neat Python Debugging Trick

Debugging python is a pretty painless experience using pdb, the built in standard debugger. The basic usage is to insert breakpoints in the code:

import pdb

print('hello world')
print('entering breakpoint')
sum = 0
for x in range(0, 10):
    sum += x

When the interpreter hits ‘pdb.set_trace()’ it’ll launch the interactive debugging interface, which lets you investigate the different variables, print things and run calculations. A tutorial on using pdb can be found here.

A really useful trick using this snippet allows for quick debugging anywhere in your code. Place the following lines at the top of your python script:

import signal
    def int_handler(signal, frame):
       import pdb
signal.signal(signal.SIGINT, int_handler)
Then run the script, and wherever you want to start a debugger press ‘ctrl’+’c’. Press ‘c’ to carry on with execution. Really useful for unpredictable bugs!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s