By continuing to navigate on this website, you accept the use of cookies to serve you more relevant services & content .
For more information and to change the setting of cookies on your computer, please read our Cookie Policy.

Debugging in Python

When something goes wrong with your code instead of using standard debugging techniques such as print statements use debugging tools. I found two great tools for debugging.

  1. using the code module.
  2. pdb module.

1.using code module: This is very useful if your code working with out errors but dint give expected result.The code module has a function interact() which stops the program execution and opens a interactive python console that inherits the local scope of the line where the interact() method is called. In that console you can print variable values(instead of placing print statements in your code),examine the state of your code and fix the bug. Place the following line in your code where you want console to start.

import code
code.interact(local=locals())

To exit the interactive console and continue with execution use Ctrl+D or Ctrl+Z or exit(). Lets have a look at following example.

#file: inc.py

def testing():
    print 'before interact'
    a=10
    b=20
    c=a+b
    import code; code.interact(local=locals())
    print 'after interact'

testing()

The output is shown below:

ramya@ramya-ws:~/Desktop$ python inc.py
before interact
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type 'help', 'copyright', 'credits' or 'license' for more information.
(InteractiveConsole)
>>> print c
30
>>> print a
10
>>> print b
20
>>>
after interact
ramya@ramya-ws:~/Desktop$
    Posted On
  • 21 November 2010
  • By
  • Micropyramid

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
QRCode generation in python

A Quick Response code(QRCode) is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules ...

Continue Reading...
Python using yield and generators.

Generators are memory efficient. They allow us to code with minimum intermediate arguments, less data structures. Generators are of two types, generator expressions and generator ...

Continue Reading...
Vim for Python Web Development

Having a good environment setup is important for effective, fast and easy coding. We have different IDE's like eclipse, pycharm, sublime etc.. which are powerful ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties