()
| 145 | # ____________________________________________________________ |
| 146 | |
| 147 | def main(): |
| 148 | import os |
| 149 | import sys |
| 150 | import runpy |
| 151 | import pstats |
| 152 | from optparse import OptionParser |
| 153 | usage = "cProfile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..." |
| 154 | parser = OptionParser(usage=usage) |
| 155 | parser.allow_interspersed_args = False |
| 156 | parser.add_option('-o', '--outfile', dest="outfile", |
| 157 | help="Save stats to <outfile>", default=None) |
| 158 | parser.add_option('-s', '--sort', dest="sort", |
| 159 | help="Sort order when printing to stdout, based on pstats.Stats class", |
| 160 | default=2, |
| 161 | choices=sorted(pstats.Stats.sort_arg_dict_default)) |
| 162 | parser.add_option('-m', dest="module", action="store_true", |
| 163 | help="Profile a library module", default=False) |
| 164 | |
| 165 | if not sys.argv[1:]: |
| 166 | parser.print_usage() |
| 167 | sys.exit(2) |
| 168 | |
| 169 | (options, args) = parser.parse_args() |
| 170 | sys.argv[:] = args |
| 171 | |
| 172 | # The script that we're profiling may chdir, so capture the absolute path |
| 173 | # to the output file at startup. |
| 174 | if options.outfile is not None: |
| 175 | options.outfile = os.path.abspath(options.outfile) |
| 176 | |
| 177 | if len(args) > 0: |
| 178 | if options.module: |
| 179 | code = "run_module(modname, run_name='__main__')" |
| 180 | globs = { |
| 181 | 'run_module': runpy.run_module, |
| 182 | 'modname': args[0] |
| 183 | } |
| 184 | else: |
| 185 | progname = args[0] |
| 186 | sys.path.insert(0, os.path.dirname(progname)) |
| 187 | with io.open_code(progname) as fp: |
| 188 | code = compile(fp.read(), progname, 'exec', module='__main__') |
| 189 | spec = importlib.machinery.ModuleSpec(name='__main__', loader=None, |
| 190 | origin=progname) |
| 191 | module = importlib.util.module_from_spec(spec) |
| 192 | # Set __main__ so that importing __main__ in the profiled code will |
| 193 | # return the same namespace that the code is executing under. |
| 194 | sys.modules['__main__'] = module |
| 195 | # Ensure that we're using the same __dict__ instance as the module |
| 196 | # for the global variables so that updates to globals are reflected |
| 197 | # in the module's namespace. |
| 198 | globs = module.__dict__ |
| 199 | globs.update({ |
| 200 | '__spec__': spec, |
| 201 | '__file__': spec.origin, |
| 202 | '__name__': spec.name, |
| 203 | '__package__': None, |
| 204 | }) |
no test coverage detected
searching dependent graphs…