DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Remote Debugging In Python - Using PDB

04.27.2009
| 11639 views |
  • submit to reddit
        Useful class for debugging Python processes to which you do not have TTY access. The example which comes to mind is CGI scripts. 
Nothing all that clever or special. Requires pdb.py from Python2.6

#!/usr/bin/env python

import pdb
import socket
import sys

class Rdb(pdb.Pdb):
  def __init__(self, port=4444):
    self.old_stdout = sys.stdout
    self.old_stdin = sys.stdin
    self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.skt.bind((socket.gethostname(), port))
    self.skt.listen(1)
    (clientsocket, address) = self.skt.accept()
    handle = clientsocket.makefile('rw')
    pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle)
    sys.stdout = sys.stdin = handle

  def do_continue(self, arg):
    sys.stdout = self.old_stdout
    sys.stdin = self.old_stdin
    self.skt.close()
    self.set_continue()
    return 1

  do_c = do_cont = do_continue


# Example usage - connect with 'telnet <hostname> 4444'
if __name__=='__main__':
  def buggy_method():
    x = 3
    remote_debug = Rdb()
    remote_debug.set_trace()
    print x

  buggy_method()