Platinum Partner

Remote Debugging In Python - Using PDB

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  4444'
if __name__=='__main__':
  def buggy_method():
    x = 3
    remote_debug = Rdb()
    remote_debug.set_trace()
    print x

  buggy_method()
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}