blob: 7e39d98579e5005f56cefc617aa7d58ca9c51af4 [file] [log] [blame]
Skip Montanaro4aba6f52004-01-26 19:44:48 +00001#!/usr/bin/env python
2# -*- coding: iso-8859-1 -*-
3
4"""
5Run a Python script under hotshot's control.
6
7Adapted from a posting on python-dev by Walter Dörwald
8
9usage %prog [ %prog args ] filename [ filename args ]
10
11Any arguments after the filename are used as sys.argv for the filename.
12"""
13
14import sys
15import optparse
16import os
17import hotshot
18import hotshot.stats
19
20PROFILE = "hotshot.prof"
21
22def run_hotshot(filename, profile, args):
23 prof = hotshot.Profile(profile)
24 sys.path.insert(0, os.path.dirname(filename))
25 sys.argv = [filename] + args
Neal Norwitz01688022007-08-12 00:43:29 +000026 fp = open(filename)
27 try:
28 script = fp.read()
29 finally:
30 fp.close()
31 prof.run("exec(%r)" % script)
Skip Montanaro4aba6f52004-01-26 19:44:48 +000032 prof.close()
33 stats = hotshot.stats.load(profile)
34 stats.sort_stats("time", "calls")
35
36 # print_stats uses unadorned print statements, so the only way
37 # to force output to stderr is to reassign sys.stdout temporarily
38 save_stdout = sys.stdout
39 sys.stdout = sys.stderr
40 stats.print_stats()
41 sys.stdout = save_stdout
42
43 return 0
44
45def main(args):
46 parser = optparse.OptionParser(__doc__)
Skip Montanaro8107ca42004-08-24 14:26:43 +000047 parser.disable_interspersed_args()
Skip Montanaro4aba6f52004-01-26 19:44:48 +000048 parser.add_option("-p", "--profile", action="store", default=PROFILE,
49 dest="profile", help='Specify profile file to use')
50 (options, args) = parser.parse_args(args)
51
52 if len(args) == 0:
53 parser.print_help("missing script to execute")
54 return 1
55
56 filename = args[0]
57 return run_hotshot(filename, options.profile, args[1:])
58
59if __name__ == "__main__":
60 sys.exit(main(sys.argv[1:]))