Skip to content

Commit

Permalink
Add ability to run statprof as a module.
Browse files Browse the repository at this point in the history
  • Loading branch information
nvie authored and jstasiak committed Oct 8, 2014
1 parent ef244f7 commit bc3368e
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion statprof.py
Expand Up @@ -106,6 +106,7 @@

import os
import signal
import sys

from collections import defaultdict
from contextlib import contextmanager
Expand Down Expand Up @@ -365,7 +366,6 @@ def p(whatever):
print(whatever, file=fp)

if fp is None:
import sys
fp = sys.stdout
if state.sample_count == 0:
p('No samples recorded.')
Expand Down Expand Up @@ -488,3 +488,28 @@ def p(whatever):
call.self_secs_in_proc,
call.lineno,
source))


def main():
'''Run the given script under the profiler, when invoked as a module
(python -m statprof ...), and display the profile report once done.
'''
if not sys.argv[1:] or sys.argv[1] in ('--help', '-h'):
print('usage: python -m statprof <script> [<args>]')
sys.exit(2)

scriptfile = sys.argv[1]
if not os.path.exists(scriptfile):
print('Error: %s does not exist' % (scriptfile,))
sys.exit(1)

del sys.argv[0] # Hide 'statprof' from argument list

# Replace statprof's dir with script's dir in front of module search path
sys.path[0] = os.path.dirname(scriptfile)

with profile():
execfile(scriptfile)

if __name__ == '__main__':
main()

0 comments on commit bc3368e

Please sign in to comment.