/Tools/scripts/hotshotmain.py

http://unladen-swallow.googlecode.com/ · Python · 55 lines · 40 code · 4 blank · 11 comment · 1 complexity · 9e7ad146000e406d1cdab0f8f2310955 MD5 · raw file

  1. #!/usr/bin/env python
  2. # -*- coding: iso-8859-1 -*-
  3. """
  4. Run a Python script under hotshot's control.
  5. Adapted from a posting on python-dev by Walter Dörwald
  6. usage %prog [ %prog args ] filename [ filename args ]
  7. Any arguments after the filename are used as sys.argv for the filename.
  8. """
  9. import sys
  10. import optparse
  11. import os
  12. import hotshot
  13. import hotshot.stats
  14. PROFILE = "hotshot.prof"
  15. def run_hotshot(filename, profile, args):
  16. prof = hotshot.Profile(profile)
  17. sys.path.insert(0, os.path.dirname(filename))
  18. sys.argv = [filename] + args
  19. prof.run("execfile(%r)" % filename)
  20. prof.close()
  21. stats = hotshot.stats.load(profile)
  22. stats.sort_stats("time", "calls")
  23. # print_stats uses unadorned print statements, so the only way
  24. # to force output to stderr is to reassign sys.stdout temporarily
  25. save_stdout = sys.stdout
  26. sys.stdout = sys.stderr
  27. stats.print_stats()
  28. sys.stdout = save_stdout
  29. return 0
  30. def main(args):
  31. parser = optparse.OptionParser(__doc__)
  32. parser.disable_interspersed_args()
  33. parser.add_option("-p", "--profile", action="store", default=PROFILE,
  34. dest="profile", help='Specify profile file to use')
  35. (options, args) = parser.parse_args(args)
  36. if len(args) == 0:
  37. parser.print_help("missing script to execute")
  38. return 1
  39. filename = args[0]
  40. return run_hotshot(filename, options.profile, args[1:])
  41. if __name__ == "__main__":
  42. sys.exit(main(sys.argv[1:]))