Debian Codegraph @

pyinstrument/__main__.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import fnmatch
4 import glob
5 import json
6 import optparse
7 import os
8 import runpy
9 import shutil
10 import sys
11 import time
12 from typing import Any, List, TextIO, cast
13
14 import pyinstrument
15 from pyinstrument import Profiler, renderers
16 from pyinstrument.session import Session
17 from pyinstrument.util import (
18 file_is_a_tty,
19 file_supports_color,
20 file_supports_unicode,
21 object_with_import_path,
22 )
23 from pyinstrument.vendor import appdirs, keypath
24
25 # pyright: strict
26 # pyright: reportUnknownMemberType=false
27
28
29 def main():
30 usage = "usage: pyinstrument [options] scriptfile [arg] ..."
31 version_string = "pyinstrument {v}, on Python {pyv[0]}.{pyv[1]}.{pyv[2]}".format(
32 v=pyinstrument.__version__,
33 pyv=sys.version_info,
34 )
35 parser: Any = optparse.OptionParser(usage=usage, version=version_string)
36 parser.allow_interspersed_args = False
37
38 def store_and_consume_remaining(
39 option: optparse.Option, opt: str, value: str, parser: optparse.OptionParser
40 ):
41 """
42 A callback for optparse that stores the value and consumes all
43 remaining arguments, storing them in the same variable as a tuple.
44 """
45
46 # assert a few things we know to be true about the parser
47 assert option.dest
48 assert parser.rargs is not None
49 assert parser.largs is not None
50
51 # everything after this argument should be consumed
52 remaining_arguments = parser.rargs + parser.largs
53 parser.rargs[:] = []
54 parser.largs[:] = []
55
56 setattr(parser.values, option.dest, ValueWithRemainingArgs(value, remaining_arguments))
57
58 parser.add_option(
59 "--load",
60 dest="load",
61 action="store",
62 metavar="FILENAME",
63 help="instead of running a script, load a profile session from a pyisession file",
64 )
65
66 parser.add_option(
67 "",
68 "--load-prev",
69 dest="load_prev",
70 action="store",
71 metavar="IDENTIFIER",
72 help="instead of running a script, load a previous profile session as specified by an identifier",
73 )
74
75 parser.add_option(
76 "-m",
77 "",
78 dest="module",
79 action="callback",
80 callback=store_and_consume_remaining,
81 type="string",
82 help="run library module as a script, like 'python -m module'",
83 )
84 parser.add_option(
85 "-c",
86 "",
87 dest="program",
88 action="callback",
89 callback=store_and_consume_remaining,
90 type="string",
91 help="program passed in as string, like 'python -c \"...\"'",
92 )
93 parser.add_option(
94 "",
95 "--from-path",
96 dest="from_path",
97 action="store_true",
98 help="(POSIX only) instead of the working directory, look for scriptfile in the PATH environment variable",
99 )
100
101 parser.add_option(
102 "-o", "--outfile", dest="outfile", action="store", help="save to <outfile>", default=None
103 )
104
105 parser.add_option(
106 "-r",
107 "--renderer",
108 dest="renderer",
109 action="store",
110 type="string",
111 help=(
112 "how the report should be rendered. One of: 'text', 'html', 'json', 'speedscope', "
113 "'pyisession', 'pstats', or python import path to a renderer class. Defaults to "
114 "the appropriate format for the extension if OUTFILE is given, otherwise, defaults "
115 "to 'text'."
116 ),
117 default=None,
118 )
119
120 parser.add_option(
121 "-p",
122 "--render-option",
123 dest="render_options",
124 action="append",
125 metavar="RENDER_OPTION",
126 type="string",
127 help=(
128 "options to pass to the renderer, in the format 'flag_name' or 'option_name=option_value'. "
129 "For example, to set the option 'time', pass '-p time=percent_of_total'. To pass multiple "
130 "options, use the -p option multiple times. You can set processor options using dot-syntax, "
131 "like '-p processor_options.filter_threshold=0'. option_value is parsed as a JSON value or "
132 "a string."
133 ),
134 )
135
136 parser.add_option(
137 "",
138 "--html",
139 dest="output_html",
140 action="store_true",
141 help=optparse.SUPPRESS_HELP,
142 default=False,
143 ) # deprecated shortcut for --renderer=html
144
145 parser.add_option(
146 "-t",
147 "--timeline",
148 dest="timeline",
149 action="store_true",
150 default=False,
151 help="render as a timeline - preserve ordering and don't condense repeated calls",
152 )
153
154 parser.add_option(
155 "",
156 "--target-description",
157 dest="target_description",
158 action="store",
159 type="string",
160 default="Program: {args}",
161 help=(
162 "description text to display in the report. The placeholder '{args}' may be used "
163 "to include the CLI arguments passed to the target script, including "
164 "the script name. Default: 'Program: {args}'"
165 ),
166 )
167
168 parser.add_option(
169 "",
170 "--hide",
171 dest="hide_fnmatch",
172 action="store",
173 metavar="EXPR",
174 help=(
175 "glob-style pattern matching the file paths whose frames to hide. Defaults to "
176 "hiding non-application code"
177 ),
178 )
179 parser.add_option(
180 "",
181 "--hide-regex",
182 dest="hide_regex",
183 action="store",
184 metavar="REGEX",
185 help=(
186 "regex matching the file paths whose frames to hide. Useful if --hide doesn't give "
187 "enough control."
188 ),
189 )
190
191 parser.add_option(
192 "",
193 "--show",
194 dest="show_fnmatch",
195 action="store",
196 metavar="EXPR",
197 help=(
198 "glob-style pattern matching the file paths whose frames to "
199 "show, regardless of --hide or --hide-regex. For example, use "
200 "--show '*/<library>/*' to show frames within a library that "
201 "would otherwise be hidden."
202 ),
203 )
204 parser.add_option(
205 "",
206 "--show-regex",
207 dest="show_regex",
208 action="store",
209 metavar="REGEX",
210 help=(
211 "regex matching the file paths whose frames to always show. "
212 "Useful if --show doesn't give enough control."
213 ),
214 )
215 parser.add_option(
216 "",
217 "--show-all",
218 dest="show_all",
219 action="store_true",
220 help="show everything",
221 default=False,
222 )
223
224 parser.add_option(
225 "",
226 "--unicode",
227 dest="unicode",
228 action="store_true",
229 help="(text renderer only) force unicode text output",
230 )
231 parser.add_option(
232 "",
233 "--no-unicode",
234 dest="unicode",
235 action="store_false",
236 help="(text renderer only) force ascii text output",
237 )
238
239 parser.add_option(
240 "",
241 "--color",
242 dest="color",
243 action="store_true",
244 help="(text renderer only) force ansi color text output",
245 )
246 parser.add_option(
247 "",
248 "--no-color",
249 dest="color",
250 action="store_false",
251 help="(text renderer only) force no color text output",
252 )
253 parser.add_option(
254 "-i",
255 "--interval",
256 action="store",
257 type=float,
258 help=(
259 "Minimum time, in seconds, between each stack sample. Smaller values "
260 "allow resolving shorter duration function calls but incur a "
261 "greater runtime and memory consumption overhead. For longer running "
262 "scripts, setting a larger interval reduces the memory consumption "
263 "required to store the stack samples."
264 ),
265 default=0.001,
266 )
267 parser.add_option(
268 "",
269 "--use-timing-thread",
270 dest="use_timing_thread",
271 action="store_true",
272 help=(
273 "Use a separate thread to time the interval between stack samples. "
274 "This can reduce the overhead of sampling on some systems."
275 ),
276 )
277
278 # parse the options
279
280 if not sys.argv[1:]:
281 parser.print_help()
282 sys.exit(2)
283
284 options, args = parser.parse_args() # type: ignore
285
286 # make command line options type-checked
287 options = cast(CommandLineOptions, options)
288 # work around a type checking bug...
289 args = cast(List[str], args) # type: ignore
290
291 session_options_used = [
292 options.load is not None,
293 options.load_prev is not None,
294 options.module is not None,
295 options.program is not None,
296 len(args) > 0,
297 ]
298 if session_options_used.count(True) == 0:
299 parser.print_help()
300 sys.exit(2)
301 if session_options_used.count(True) > 1:
302 parser.error("You can only specify one of --load, --load-prev, -m, or script arguments")
303
304 if options.module is not None and options.from_path:
305 parser.error("The options -m and --from-path are mutually exclusive.")
306
307 if options.from_path and sys.platform == "win32":
308 parser.error("--from-path is not supported on Windows")
309
310 renderer_class = get_renderer_class(options)
311
312 # open the output file
313
314 if options.outfile:
315 f = open(
316 options.outfile,
317 "w",
318 encoding="utf-8",
319 errors="surrogateescape",
320 newline="" if renderer_class.output_is_binary else None,
321 )
322 should_close_f_after_writing = True
323 else:
324 f = sys.stdout
325 should_close_f_after_writing = False
326
327 inner_exception = None
328
329 # create the renderer
330
331 try:
332 renderer = create_renderer(renderer_class, options, output_file=f)
333 except OptionsParseError as e:
334 parser.error(e.args[0])
335 exit(1)
336
337 if renderer.output_is_binary and not options.outfile and file_is_a_tty(f):
338 parser.error(
339 "Can't write binary output to a terminal. Redirect to a file or use --outfile."
340 )
341 exit(1)
342
343 # get the session - execute code or load from disk
344
345 if options.load_prev:
346 session = load_report_from_temp_storage(options.load_prev)
347 elif options.load:
348 session = Session.load(options.load)
349 else:
350 # we are running some code
351 if options.module is not None:
352 if not (sys.path[0] and os.path.samefile(sys.path[0], ".")):
353 # when called with '-m', search the cwd for that module
354 sys.path[0] = os.path.abspath(".")
355
356 argv = [options.module.value] + options.module.remaining_args
357 code = "run_module(modname, run_name='__main__', alter_sys=True)"
358 globs = {"run_module": runpy.run_module, "modname": options.module.value}
359 elif options.program is not None:
360 argv = ["-c", *options.program.remaining_args]
361 code = options.program.value
362 globs = {"__name__": "__main__"}
363 # set the first path entry to '' to match behaviour of python -c
364 sys.path[0] = ""
365 else:
366 argv = args
367 if options.from_path:
368 progname = shutil.which(args[0])
369 if progname is None:
370 sys.exit(f"Error: program {args[0]} not found in PATH!")
371 else:
372 progname = args[0]
373 if not os.path.exists(progname):
374 sys.exit(f"Error: program {args[0]} not found!")
375
376 # Make sure we overwrite the first entry of sys.path ('.') with directory of the program.
377 sys.path[0] = os.path.dirname(progname)
378
379 code = "run_path(progname, run_name='__main__')"
380 globs = {"run_path": runpy.run_path, "progname": progname}
381
382 old_argv = sys.argv.copy()
383
384 # there is no point using async mode for command line invocation,
385 # because it will always be capturing the whole program, we never want
386 # any execution to be <out-of-context>, and it avoids duplicate
387 # profiler errors.
388 profiler = Profiler(
389 interval=options.interval,
390 async_mode="disabled",
391 use_timing_thread=options.use_timing_thread,
392 )
393
394 try:
395 target_description = options.target_description.format(args=" ".join(argv))
396 except KeyError as e:
397 parser.error(f"Unknown placeholder {e.args[0]!r} in --target-description")
398 # explicitly add exit() so that pyright doesn't complain, even
399 # though parser.error already exits with error code 2
400 exit(2)
401 except IndexError as e:
402 parser.error(f"Empty placeholder in --target-description")
403 exit(2)
404
405 profiler.start(target_description=target_description)
406
407 try:
408 sys.argv[:] = argv
409 exec(code, globs, None)
410 except (SystemExit, KeyboardInterrupt) as e:
411 inner_exception = e
412 finally:
413 sys.argv[:] = old_argv
414
415 session = profiler.stop()
416
417 if isinstance(renderer, renderers.HTMLRenderer) and not options.outfile and file_is_a_tty(f):
418 # don't write HTML to a TTY, open in browser instead
419 output_filename = renderer.open_in_browser(session)
420 print("stdout is a terminal, so saved profile output to %s" % output_filename)
421 else:
422 f.write(renderer.render(session))
423 if should_close_f_after_writing:
424 f.close()
425
426 if isinstance(renderer, renderers.ConsoleRenderer) and not options.outfile:
427 _, report_identifier = save_report_to_temp_storage(session)
428 print("To view this report with different options, run:")
429 print(" pyinstrument --load-prev %s [options]" % report_identifier)
430 print("")
431
432 if inner_exception:
433 # If the script raised an exception, re-raise it now to resume
434 # the normal Python exception handling (printing the traceback, etc.)
435 raise inner_exception
436
437
438 class OptionsParseError(Exception):
439 pass
440
441
442 def compute_render_options(
443 options: CommandLineOptions,
444 renderer_class: type[renderers.Renderer],
445 unicode_support: bool,
446 color_support: bool,
447 ) -> dict[str, Any]:
448 """
449 Given a list of `CommandLineOptions`, compute the
450 rendering options for the given renderer.
451
452 Raises an `OptionsParseError` if there is an error parsing the options.
453
454 unicode_support:
455 indicate whether the expected output supports unicode
456 color_support:
457 indicate whether the expected output supports color
458
459 Both of these will be used to determine the default of outputting unicode
460 or color, but can be overridden with `options.color` and `option.unicode`.
461 """
462
463 # parse show/hide options
464 if options.hide_fnmatch is not None and options.hide_regex is not None:
465 raise OptionsParseError("You can‘t specify both --hide and --hide-regex")
466
467 hide_regex: str | None
468 show_regex: str | None
469 if options.hide_fnmatch is not None:
470 hide_regex = fnmatch.translate(options.hide_fnmatch)
471 else:
472 hide_regex = options.hide_regex
473
474 show_options_used = [
475 options.show_fnmatch is not None,
476 options.show_regex is not None,
477 options.show_all,
478 ]
479 if show_options_used.count(True) > 1:
480 raise OptionsParseError("You can only specify one of --show, --show-regex and --show-all")
481
482 if options.show_fnmatch is not None:
483 show_regex = fnmatch.translate(options.show_fnmatch)
484 elif options.show_all:
485 show_regex = r".*"
486 else:
487 show_regex = options.show_regex
488
489 render_options: dict[str, Any] = {}
490
491 if issubclass(renderer_class, renderers.FrameRenderer):
492 render_options["processor_options"] = {
493 "hide_regex": hide_regex,
494 "show_regex": show_regex,
495 }
496
497 if issubclass(renderer_class, renderers.ConsoleRenderer):
498 unicode_override = options.unicode is not None
499 color_override = options.color is not None
500 unicode: Any = options.unicode if unicode_override else unicode_support
501 color: Any = options.color if color_override else color_support
502
503 render_options.update({"unicode": unicode, "color": color})
504
505 if options.timeline:
506 render_options["timeline"] = True
507 if options.show_all:
508 render_options["show_all"] = True
509
510 # apply user options
511 if options.render_options is not None:
512 for renderer_option in options.render_options:
513 key, sep, value = renderer_option.partition("=")
514
515 if sep == "":
516 # we're setting a flag, like `-p unicode`
517 keypath.set_value_at_keypath(render_options, key, True)
518 else:
519 # it's a key=value structure
520 try:
521 # try parsing as a JSON value
522 parsed_value = json.loads(value)
523 except json.JSONDecodeError:
524 # otherwise treat it as a string
525 parsed_value = value
526
527 keypath.set_value_at_keypath(render_options, key, parsed_value)
528
529 return render_options
530
531
532 def create_renderer(
533 renderer_class: type[renderers.Renderer], options: CommandLineOptions, output_file: TextIO
534 ) -> renderers.Renderer:
535 render_options = compute_render_options(
536 options,
537 renderer_class=renderer_class,
538 unicode_support=file_supports_unicode(output_file),
539 color_support=file_supports_color(output_file),
540 )
541
542 try:
543 return renderer_class(**render_options)
544 except (TypeError, renderers.Renderer.MisconfigurationError) as err:
545 # TypeError is probably a bad renderer option, so we produce a nicer error message
546 raise OptionsParseError(
547 f"Failed to create {renderer_class.__name__}. Check your renderer options.\n {err}\n"
548 )
549
550
551 def get_renderer_class(options: CommandLineOptions) -> type[renderers.Renderer]:
552 renderer = options.renderer
553
554 if options.output_html:
555 renderer = "html"
556
557 if renderer is None and options.outfile:
558 renderer = guess_renderer_from_outfile(options.outfile)
559
560 if renderer is None:
561 renderer = "text"
562
563 if renderer == "text":
564 return renderers.ConsoleRenderer
565 elif renderer == "html":
566 return renderers.HTMLRenderer
567 elif renderer == "json":
568 return renderers.JSONRenderer
569 elif renderer == "speedscope":
570 return renderers.SpeedscopeRenderer
571 elif renderer == "pyisession" or renderer == "session": # session is the old name
572 return renderers.SessionRenderer
573 elif renderer == "pstats":
574 return renderers.PstatsRenderer
575 else:
576 try:
577 return object_with_import_path(renderer)
578 except (ValueError, ModuleNotFoundError, AttributeError) as err:
579 # ValueError means we failed to import this object
580 raise OptionsParseError(
581 f"Failed to find renderer with name {renderer!r}.\n"
582 "Options are text, html, json, speedscope, pstats or a Python\n"
583 "import path to a Renderer class.\n"
584 "\n"
585 f"Underlying error: {err}\n"
586 )
587
588
589 def guess_renderer_from_outfile(outfile: str) -> str | None:
590 # ignore case of outfile
591 outfile = outfile.lower()
592
593 _, ext = os.path.splitext(outfile)
594
595 if ext == ".txt":
596 return "text"
597 elif ext in [".html", ".htm"]:
598 return "html"
599 elif outfile.endswith(".speedscope.json"):
600 return "speedscope"
601 elif ext == ".json":
602 return "json"
603 elif ext == ".pyisession":
604 return "session"
605 elif ext == ".pstats":
606 return "pstats"
607 else:
608 return None
609
610
611 def report_dir() -> str:
612 data_dir = appdirs.user_data_dir("pyinstrument", "com.github.joerick") # type: ignore
613 report_dir = os.path.join(data_dir, "reports")
614 if not os.path.exists(report_dir):
615 os.makedirs(report_dir)
616 return report_dir
617
618
619 def load_report_from_temp_storage(identifier: str) -> Session:
620 """
621 Returns the session referred to by identifier
622 """
623 path = os.path.join(report_dir(), identifier + ".pyisession")
624 try:
625 return Session.load(path)
626 except FileNotFoundError:
627 sys.exit(f"pyinstrument: Couldn't find a profile with identifier {identifier}")
628
629
630 def save_report_to_temp_storage(session: Session):
631 """
632 Saves the session to a temp file, and returns that path.
633 Also prunes the number of reports to 10 so there aren't loads building up.
634 """
635 # prune this folder to contain the last 10 sessions
636 previous_reports = glob.glob(os.path.join(report_dir(), "*.pyisession"))
637 previous_reports.sort(reverse=True)
638 while len(previous_reports) > 10:
639 report_file = previous_reports.pop()
640 os.remove(report_file)
641
642 identifier = time.strftime("%Y-%m-%dT%H-%M-%S", time.localtime(session.start_time))
643
644 path = os.path.join(report_dir(), identifier + ".pyisession")
645 session.save(path)
646 return path, identifier
647
648
649 class CommandLineOptions:
650 """
651 A type that codifies the `options` variable.
652 """
653
654 module: ValueWithRemainingArgs | None
655 program: ValueWithRemainingArgs | None
656 load: str | None
657 load_prev: str | None
658 from_path: str | None
659 hide_fnmatch: str | None
660 show_fnmatch: str | None
661 hide_regex: str | None
662 show_regex: str | None
663 show_all: bool
664 output_html: bool
665 outfile: str | None
666 render_options: list[str] | None
667 target_description: str
668
669 unicode: bool | None
670 color: bool | None
671 renderer: str | None
672 timeline: bool
673 interval: float
674 use_timing_thread: bool | None
675
676
677 class ValueWithRemainingArgs:
678 def __init__(self, value: str, remaining_args: list[str]):
679 self.value = value
680 self.remaining_args = remaining_args
681
682
683 if __name__ == "__main__":
684 main()