#! /usr/bin/python2.2
#
# Command-line interface to HotShot profiler.
#
# Covered by Python 2.2's license and copyright (see www.python.org).

import sys
import os
import time
import marshal
import tempfile

__all__ = ["run","help","Profile"]

from hotshot import Profile
import hotshot.stats

def run(statement):
    """Run statement under profiler optionally saving results in filename

    This function takes a single argument that can be passed to the
    "exec" statement, and an optional file name.  In all cases this
    routine attempts to "exec" its first argument and gather profiling
    statistics from the execution. If no file name is present, then this
    function automatically prints a simple profiling report, sorted by the
    standard name string (file/line/function-name) that is presented in
    each line.
    """
    filename = tempfile.mktemp()
    prof = Profile(filename)
    try:
        prof = prof.run(statement)
    except SystemExit:
        pass
    
    s = hotshot.stats.load(filename)
    return s.strip_dirs().sort_stats(-1).print_stats()

# When invoked as main program, invoke the profiler on a script
if __name__ == '__main__':
    if not sys.argv[1:]:
        print "usage: hotshot_profile.py scriptfile [arg] ..."
        sys.exit(2)

    filename = sys.argv[1]  # Get script filename

    del sys.argv[0]         # Hide "profile.py" from argument list

    # Insert script directory in front of module search path
    sys.path.insert(0, os.path.dirname(filename))

    run('execfile(' + `filename` + ')')
