10min python: settrace

10min python:

what is settrace?

settrace traces each execution instruction of python script

Where we can use it?

If you want to trace the execution sequence and it’s control over your entire script, this should be the right utility.It does similar to Django’s middleware property

How to use it?

import sys

def callback(frame, event, arg):
    '''
    do your magic using frame, event, arg
    '''

sys.settrace(callback)
#your script starts from here

example?

import sys


def mycallback(frame, event, arg):
    print "event is %s" %event
    print "args are %s" %arg
    print "current exe line funcname: %s" %frame.f_code.co_name
    print "current execution line: %s" %frame.f_lineno
    print "caller line no: %s" %frame.f_back.f_lineno
    print "caller file name: %s" %frame.f_back.f_code.co_name
    '''
    return callback function is important to trace the sequence of all instraction from entry to exit, if return is `None` only one instruction will be traced
    '''
    return mycallback 


def function(arg1, arg2):
    print "Input: ",arg1, arg2
    return arg1 + arg2

sys.settrace(mycallback)
print function(4,5)
sys.settrace(None)

output

settrace in pythonkudos links:

http://pymotw.com/2/sys/tracing.html

bye bye!

 

Advertisements

About Navaneethan

mixed feelings...
This entry was posted in 10min, Academic, Python and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s