23 Jan 2008

23Jan08

Tracing python programs. Today, Evan Dandrea asked a general question “Where is set -x for python”. A quick google for sys.settrace found: Some code snippets. I thought this was nice, but surely you want to be able to just trace an arbitrary program. So I present a ‘quick hack’ (5 minutes precisely :)) to do that based on the previous links final version:

 #!/usr/bin/env python 

import linecache import os import os.path import sys

def traceit(frame, event, arg): if event == "line": lineno = frame.f_lineno filename = frame.f_globals["__file__"] if (filename.endswith(".pyc") or filename.endswith(".pyo")): filename = filename[:-1] name = frame.f_globals["__name__"] line = linecache.getline(filename, lineno) print "%s:%s: %s" % (name, lineno, line.rstrip()) return traceit

def main(): search_path = os.environ.get('PATH', '').split(os.path.pathsep) argv = sys.argv[1:] if not argv: raise Exception("No command to trace supplied") args = argv[1:] command = argv[0] if os.path.sep not in command: for path in search_path: if os.path.exists(os.path.join(path, command)): command = os.path.join(path, command) break del sys.argv[0] source = open(command, 'rt') exec_symbols = dict(globals()) exec_symbols['__name__'] = '__main__' sys.settrace(traceit) exec source in exec_symbols, exec_symbols

main()

About these ads


No Responses Yet to “23 Jan 2008”

  1. Leave a Comment

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


Follow

Get every new post delivered to your Inbox.

Join 1,046 other followers

%d bloggers like this: