Friday, February 12, 2010

python: call function stored in string variable

In the following, op1 and op2 are strings containing function names (e.g. 'stop', 'enable', 'disable') to be invoked:

def start():
    print 'INFO|start()|starting identity %s.%s' %(name1, domain)
def stop():
    print 'INFO|start()|starting identity %s.%s' %(name1, domain)
def enable():
    print 'INFO|enable()|enabling identity %s.%s' %(name1, domain)
def disable():
    print 'INFO|disable()|disabling identity %s.%s' %(name1, domain)

function_mapper = { 'stop':stop,
                    'start':start,
                    'enable':enable,
                    'disable':disable
                  }


def main():
    newlist = ['start', 'disable', 'enable']
    print '\n\n', newlist

    for op2 in newlist:
    for op1 in newlist:
    function_mapper[op1]()
    function_mapper[op2]()
    print "\n"

    
if __name__ == '__main__':
sys.exit( main() )

python: make an HTTP request with any kind of HTTP method (put, delete, head) using urllib2

Sometimes you don't want to sit and migrate all your existing codebase from urllib/urllib2 to httplib/httplib2, just because the former doesn't support HTTP PUT or HTTP DELETE methods out-of-the-box. Well, here's a workaround for just that problem:
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)


Thanks to stackoverflow yet again for solving another programming conundrum :)

Wednesday, February 3, 2010

linux:debugging with gdb uses sigtrap internally

SIGTRAP is used as a mechanism for a debugger to be notified when the
process it's debugging hits a breakpoint.

A typical way for something like GDB to use it would be something like
this:

- The user asks gdb to set a breakpoint at a certain address in the
  target process.  gdb uses ptrace to replace the instruction at that
  address with the "int3" instruction, which generates a debug
  exception.  It also uses ptrace to ask that the process be stopped
  when SIGTRAP is raised.
- When the target process hits that address, the exception is
  generated.  The kernel treats this as raising a SIGTRAP signal.  The
  process is stopped and gdb is notified.
- gdb lets the user examine the state of the target process.  When the
  user is ready to continue, gdb replaces the int3 with the instruction
  that had originally been there, and uses ptrace to tell the kernel to
  restart the target process from that instruction.  AFAIK it would also
  normally tell the kernel not to deliver the SIGTRAP signal to the
  process, since by default that would kill it.  
So it would normally be
  irrelevant how you are handling SIGTRAP (SIG_IGN or SIG_DFL or a
  handler) because the target will never know it occurred.

(Discovered this information thanks to bug 31715)

source