()
| 551 | #**************************************************************************** |
| 552 | |
| 553 | def main(): |
| 554 | import os |
| 555 | from optparse import OptionParser |
| 556 | |
| 557 | usage = "profile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..." |
| 558 | parser = OptionParser(usage=usage) |
| 559 | parser.allow_interspersed_args = False |
| 560 | parser.add_option('-o', '--outfile', dest="outfile", |
| 561 | help="Save stats to <outfile>", default=None) |
| 562 | parser.add_option('-m', dest="module", action="store_true", |
| 563 | help="Profile a library module.", default=False) |
| 564 | parser.add_option('-s', '--sort', dest="sort", |
| 565 | help="Sort order when printing to stdout, based on pstats.Stats class", |
| 566 | default=-1) |
| 567 | |
| 568 | if not sys.argv[1:]: |
| 569 | parser.print_usage() |
| 570 | sys.exit(2) |
| 571 | |
| 572 | (options, args) = parser.parse_args() |
| 573 | sys.argv[:] = args |
| 574 | |
| 575 | # The script that we're profiling may chdir, so capture the absolute path |
| 576 | # to the output file at startup. |
| 577 | if options.outfile is not None: |
| 578 | options.outfile = os.path.abspath(options.outfile) |
| 579 | |
| 580 | if len(args) > 0: |
| 581 | if options.module: |
| 582 | import runpy |
| 583 | code = "run_module(modname, run_name='__main__')" |
| 584 | globs = { |
| 585 | 'run_module': runpy.run_module, |
| 586 | 'modname': args[0] |
| 587 | } |
| 588 | else: |
| 589 | progname = args[0] |
| 590 | sys.path.insert(0, os.path.dirname(progname)) |
| 591 | with io.open_code(progname) as fp: |
| 592 | code = compile(fp.read(), progname, 'exec') |
| 593 | globs = { |
| 594 | '__file__': progname, |
| 595 | '__name__': '__main__', |
| 596 | '__package__': None, |
| 597 | '__cached__': None, |
| 598 | } |
| 599 | try: |
| 600 | runctx(code, globs, None, options.outfile, options.sort) |
| 601 | except BrokenPipeError as exc: |
| 602 | # Prevent "Exception ignored" during interpreter shutdown. |
| 603 | sys.stdout = None |
| 604 | sys.exit(exc.errno) |
| 605 | else: |
| 606 | parser.print_usage() |
| 607 | return parser |
| 608 | |
| 609 | # When invoked as main program, invoke the profiler on a script |
| 610 | if __name__ == '__main__': |
no test coverage detected