Debugging App Engine application with Python pdb debugger

Python comes with command line debugger pdb which is a rough, but useful, tool for Python developers.

You can insert source code breakpoints by adding into your code….

import pdb ; pdb.set_trace()

… and next time the code is run an interactive pdb prompts opens in your terminal window.

Google App Engine captures stdout and stdin system input and output streams for its internal purposes. Since pdb relies on them, pdb cannot be directly opened in App Engine. You cannot open pdb at all on the App Engine production server, as the server is little bit special due to scalability goals (no raw file system, terminal access).

However, you can still open pdb() on your local App Engine development server with the following little trick:

def dbg():
 """ Enter pdb in App Engine

 Renable system streams for it.
 """
 import pdb
 import sys
 pdb.Pdb(stdin=getattr(sys,'__stdin__'),stdout=getattr(sys,'__stderr__')).set_trace(sys._getframe().f_back)

This will grab the real system input and output stream, launch pdb() with them and step back one stack frace before calling dbg(). So you can simply add a breakpoint to your App Engine like the following:

class MainPage(BasePage):
 """ Index page of the site.

 """

 def get(self):
   logging.debug("Loading main page")
   path = os.path.join(os.path.dirname(__file__), 'index.html')
   vars = self.get_vars()
   dbg() # inspect what template variables are being passed to the template
   self.response.out.write(template.render(path, vars))

How to actual use pdb and some more pdb goodies are documented in Plone collective maintained developer manual.

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

5 thoughts on “Debugging App Engine application with Python pdb debugger

  1. Is there any reason to write getattr(sys, ‘__stdin__’) instead of sys.__stdin__?

    Also, sys._getframe(1) is shorter than sys._getframe().f_back.

  2. I believe there is no reason, except maybe there has been some old debugging code attached to it long time ago and the notation is just leftovers.

  3. Thanks i love you! this really made my day, nothing more horrible than not been able to debug your site.

  4. Any tip on where in the django project is the best place to put it?

    By the way, thanks, this is a great little tip!
    I wish google could already fix this bug in the SDK.

Leave a Reply

Your email address will not be published. Required fields are marked *