blob: 4f406284bd86592c525e65c3115de1d80e6a82dc [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
26 prof.run("execfile(%r)" % filename)
27 prof.close()
28 stats = hotshot.stats.load(profile)
29 stats.sort_stats("time", "calls")
30
31 # print_stats uses unadorned print statements, so the only way
32 # to force output to stderr is to reassign sys.stdout temporarily
33 save_stdout = sys.stdout
34 sys.stdout = sys.stderr
35 stats.print_stats()
36 sys.stdout = save_stdout
37
38 return 0
39
40def main(args):
41 parser = optparse.OptionParser(__doc__)
Skip Montanaro8107ca42004-08-24 14:26:43 +000042 parser.disable_interspersed_args()
Skip Montanaro4aba6f52004-01-26 19:44:48 +000043 parser.add_option("-p", "--profile", action="store", default=PROFILE,
44 dest="profile", help='Specify profile file to use')
45 (options, args) = parser.parse_args(args)
46
47 if len(args) == 0:
48 parser.print_help("missing script to execute")
49 return 1
50
51 filename = args[0]
52 return run_hotshot(filename, options.profile, args[1:])
53
54if __name__ == "__main__":
55 sys.exit(main(sys.argv[1:]))