()
| 129 | # ____________________________________________________________ |
| 130 | |
| 131 | def main(): |
| 132 | import os |
| 133 | import sys |
| 134 | import runpy |
| 135 | import pstats |
| 136 | from optparse import OptionParser |
| 137 | usage = "cProfile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..." |
| 138 | parser = OptionParser(usage=usage) |
| 139 | parser.allow_interspersed_args = False |
| 140 | parser.add_option('-o', '--outfile', dest="outfile", |
| 141 | help="Save stats to <outfile>", default=None) |
| 142 | parser.add_option('-s', '--sort', dest="sort", |
| 143 | help="Sort order when printing to stdout, based on pstats.Stats class", |
| 144 | default=2, |
| 145 | choices=sorted(pstats.Stats.sort_arg_dict_default)) |
| 146 | parser.add_option('-m', dest="module", action="store_true", |
| 147 | help="Profile a library module", default=False) |
| 148 | |
| 149 | if not sys.argv[1:]: |
| 150 | parser.print_usage() |
| 151 | sys.exit(2) |
| 152 | |
| 153 | (options, args) = parser.parse_args() |
| 154 | sys.argv[:] = args |
| 155 | |
| 156 | # The script that we're profiling may chdir, so capture the absolute path |
| 157 | # to the output file at startup. |
| 158 | if options.outfile is not None: |
| 159 | options.outfile = os.path.abspath(options.outfile) |
| 160 | |
| 161 | if len(args) > 0: |
| 162 | if options.module: |
| 163 | code = "run_module(modname, run_name='__main__')" |
| 164 | globs = { |
| 165 | 'run_module': runpy.run_module, |
| 166 | 'modname': args[0] |
| 167 | } |
| 168 | else: |
| 169 | progname = args[0] |
| 170 | sys.path.insert(0, os.path.dirname(progname)) |
| 171 | with io.open_code(progname) as fp: |
| 172 | code = compile(fp.read(), progname, 'exec') |
| 173 | globs = { |
| 174 | '__file__': progname, |
| 175 | '__name__': '__main__', |
| 176 | '__package__': None, |
| 177 | '__cached__': None, |
| 178 | } |
| 179 | try: |
| 180 | runctx(code, globs, None, options.outfile, options.sort) |
| 181 | except BrokenPipeError as exc: |
| 182 | # Prevent "Exception ignored" during interpreter shutdown. |
| 183 | sys.stdout = None |
| 184 | sys.exit(exc.errno) |
| 185 | else: |
| 186 | parser.print_usage() |
| 187 | return parser |
| 188 |
no test coverage detected