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 pythonimport 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()