import subprocess
import sys
import time
+import webbrowser
from contextlib import nullcontext
from .errors import SamplingUnknownProcessError, SamplingModuleNotFoundError, SamplingScriptNotFoundError
help="Output path (default: stdout for pstats, auto-generated for others). "
"For heatmap: directory name (default: heatmap_PID)",
)
+ output_group.add_argument(
+ "--browser",
+ action="store_true",
+ help="Automatically open HTML output (flamegraph, heatmap) in browser. "
+ "When using --subprocesses, only the main process opens the browser",
+ )
def _add_pstats_options(parser):
return f"{format_type}_{pid}.{extension}"
+def _open_in_browser(path):
+ """Open a file or directory in the default web browser.
+
+ Args:
+ path: File path or directory path to open
+
+ For directories (heatmap), opens the index.html file inside.
+ """
+ abs_path = os.path.abspath(path)
+
+ # For heatmap directories, open the index.html file
+ if os.path.isdir(abs_path):
+ index_path = os.path.join(abs_path, 'index.html')
+ if os.path.exists(index_path):
+ abs_path = index_path
+ else:
+ print(f"Warning: Could not find index.html in {path}", file=sys.stderr)
+ return
+
+ file_url = f"file://{abs_path}"
+ try:
+ webbrowser.open(file_url)
+ except Exception as e:
+ print(f"Warning: Could not open browser: {e}", file=sys.stderr)
+
+
def _handle_output(collector, args, pid, mode):
"""Handle output for the collector based on format and arguments.
filename = args.outfile or _generate_output_filename(args.format, pid)
collector.export(filename)
+ # Auto-open browser for HTML output if --browser flag is set
+ if args.format in ('flamegraph', 'heatmap') and getattr(args, 'browser', False):
+ _open_in_browser(filename)
+
def _validate_args(args, parser):
"""Validate format-specific options and live mode requirements.
filename = args.outfile or _generate_output_filename(args.format, os.getpid())
collector.export(filename)
+ # Auto-open browser for HTML output if --browser flag is set
+ if args.format in ('flamegraph', 'heatmap') and getattr(args, 'browser', False):
+ _open_in_browser(filename)
+
print(f"Replayed {count} samples")