3939import os
4040import time
4141import marshal
42+ from optparse import OptionParser
4243
4344__all__ = ["run" ,"help" ,"Profile" ]
4445
5556# Note that an instance of Profile() is *not* needed to call them.
5657#**************************************************************************
5758
58- def run (statement , filename = None ):
59+ def run (statement , filename = None , sort = - 1 ):
5960 """Run statement under profiler optionally saving results in filename
6061
6162 This function takes a single argument that can be passed to the
@@ -74,7 +75,7 @@ def run(statement, filename=None):
7475 if filename is not None :
7576 prof .dump_stats (filename )
7677 else :
77- return prof .print_stats ()
78+ return prof .print_stats (sort )
7879
7980def runctx (statement , globals , locals , filename = None ):
8081 """Run statement under profiler, supplying your own globals and locals,
@@ -384,9 +385,9 @@ def simulate_cmd_complete(self):
384385 self .t = get_time () - t
385386
386387
387- def print_stats (self ):
388+ def print_stats (self , sort = - 1 ):
388389 import pstats
389- pstats .Stats (self ).strip_dirs ().sort_stats (- 1 ). \
390+ pstats .Stats (self ).strip_dirs ().sort_stats (sort ). \
390391 print_stats ()
391392
392393 def dump_stats (self , file ):
@@ -556,15 +557,28 @@ def Stats(*args):
556557
557558# When invoked as main program, invoke the profiler on a script
558559if __name__ == '__main__' :
560+ usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
559561 if not sys .argv [1 :]:
560- print "usage: profile.py scriptfile [arg] ..."
562+ print "Usage: " , usage
561563 sys .exit (2 )
562564
563- filename = sys .argv [1 ] # Get script filename
564-
565- del sys .argv [0 ] # Hide "profile.py" from argument list
566-
567- # Insert script directory in front of module search path
568- sys .path .insert (0 , os .path .dirname (filename ))
569-
570- run ('execfile(%r)' % (filename ,))
565+ class ProfileParser (OptionParser ):
566+ def __init__ (self , usage ):
567+ OptionParser .__init__ (self )
568+ self .usage = usage
569+
570+ parser = ProfileParser (usage )
571+ parser .allow_interspersed_args = False
572+ parser .add_option ('-o' , '--outfile' , dest = "outfile" ,
573+ help = "Save stats to <outfile>" , default = None )
574+ parser .add_option ('-s' , '--sort' , dest = "sort" ,
575+ help = "Sort order when printing to stdout, based on pstats.Stats class" , default = - 1 )
576+
577+ (options , args ) = parser .parse_args ()
578+ sys .argv [:] = args
579+
580+ if (len (sys .argv ) > 0 ):
581+ sys .path .insert (0 , os .path .dirname (sys .argv [0 ]))
582+ run ('execfile(%r)' % (sys .argv [0 ],), options .outfile , options .sort )
583+ else :
584+ print "Usage: " , usage
0 commit comments