The trace function passed to sys.settrace.

def _trace(self, frame, event, arg_unused):
        """
        The trace function passed to sys.settrace.
        """
        cur_time = time.time()

        lineno = frame.f_lineno
        depth = self.depth

        filename = inspect.getfile(frame)

        if self.last_exc_back:
            if frame == self.last_exc_back:
                self.data['time_spent'] += (cur_time - self.start_time)
                self.depth -= 1

                self.data = self.data_stack.pop()

            self.last_exc_back = None

        if event == 'call':
            # Update our state
            self.depth += 1

            if self.log:
                print >> sys.stdout, '%s >> %s:%s' % (' ' * (depth - 1), filename, frame.f_code.co_name)

            # origin line number (where it was called from)
            o_lineno = frame.f_back.f_lineno

            if self.pause_until is not None:
                if depth == self.pause_until:
                    self.pause_until = None
                else:
                    return self._trace

            if o_lineno not in self.data['lines']:
                self.pause_until = depth

                return self._trace

            # Append it to the stack
            self.data_stack.append(self.data)

            call_sig = '%s:%s' % (inspect.getfile(frame), frame.f_code.co_name)

            if call_sig not in self.data['children']:
                self.data['children'][o_lineno][call_sig] = self._get_struct(frame, event)

            self.data = self.data['children'][o_lineno][call_sig]

            self.data['num_calls'] += 1

        elif event == 'line':
            # Record an executed line.
            if self.pause_until is None and lineno in self.data['lines']:
                self.data['lines'][lineno]['num_calls'] += 1
                self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time)

            if self.log:
                print >> sys.stdout, '%s -- %s:%s executing line %d' % (' ' * (depth - 1), filename, frame.f_code.co_name, lineno)

        elif event == 'return':
            timing = (cur_time - self.start_time)

            # Leaving this function, pop the filename stack.
            if self.pause_until is None:
                self.data['time_spent'] += timing
                self.data = self.data_stack.pop()
                self.data['time_spent'] += timing
                # self.data['lines'][lineno]['num_calls'] += 1
                # self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time)

            if self.log:
                print >> sys.stdout, '%s << %s:%s %.3fs' % (' ' * (depth - 1), filename, frame.f_code.co_name, timing)

            self.depth -= 1

        elif event == 'exception':
            self.last_exc_back = frame.f_back
            self.last_exc_firstlineno = frame.f_code.co_firstlineno

        return self._trace