Skip to content

Commit

Permalink
Merge pull request #266 from thomasaarholt/write-html
Browse files Browse the repository at this point in the history
Add method to write directly to html file
  • Loading branch information
joerick committed Oct 11, 2023
2 parents f413fda + e94b294 commit c0be3bd
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 8 deletions.
3 changes: 1 addition & 2 deletions docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,7 @@ def auto_profile(request):
profiler.stop()
PROFILE_ROOT.mkdir(exist_ok=True)
results_file = PROFILE_ROOT / f"{request.node.name}.html"
with open(results_file, "w", encoding="utf-8") as f_html:
f_html.write(profiler.output_html())
profiler.write_html(results_file)
```

This will generate a HTML file for each test node in your test suite inside
Expand Down
3 changes: 1 addition & 2 deletions metrics/interrupt.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,4 @@ def func():

print(p.output_text())

with open("ioerror_out.html", "w") as f:
f.write(p.output_html())
p.write_html("ioerror_out.html")
3 changes: 1 addition & 2 deletions metrics/overflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,4 @@ def func(num):

print(p.output_text())

with open("overflow_out.html", "w") as f:
f.write(p.output_html())
p.write_html("overflow_out.html")
3 changes: 1 addition & 2 deletions metrics/overhead.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ def test_func_template():
# pyinstrument_timeline_timings = test_func()
# profiler.stop()

with open("out.html", "w") as f:
f.write(profiler.output_html())
profiler.write_html("out.html")

print(profiler.output_text(unicode=True, color=True))

Expand Down
12 changes: 12 additions & 0 deletions pyinstrument/profiler.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import annotations

import inspect
import os
import sys
import time
import types
from pathlib import Path
from time import process_time
from typing import IO, Any

Expand Down Expand Up @@ -304,6 +306,16 @@ def output_html(self, timeline: bool = False) -> str:
"""
return self.output(renderer=renderers.HTMLRenderer(timeline=timeline))

def write_html(self, path: str | os.PathLike[str], timeline: bool = False):
"""
Writes the profile output as HTML to a file, as rendered by :class:`HTMLRenderer`
"""
file = Path(path)
file.write_text(
self.output(renderer=renderers.HTMLRenderer(timeline=timeline)),
encoding="utf-8",
)

def open_in_browser(self, timeline: bool = False):
"""
Opens the last profile session in your web browser.
Expand Down

0 comments on commit c0be3bd

Please sign in to comment.