Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions codecarbon/cli/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,12 @@ def run_and_monitor(
else:
print(" Emissions: N/A")

# Show where the data was saved
if hasattr(tracker, "_conf") and "output_file" in tracker._conf:
output_path = tracker._conf["output_file"]
# Make it absolute if it's relative
if not os.path.isabs(output_path):
output_path = os.path.abspath(output_path)
print(f" Saved to: {output_path}")
# Show where the data was saved, asking the output handlers themselves
# so the path stays right whatever `output_dir` / `output_file` are.
for handler in getattr(tracker, "_output_handlers", []):
save_file_path = getattr(handler, "save_file_path", None)
if save_file_path:
print(f" Saved to: {os.path.abspath(save_file_path)}")

print(" 鈿狅笍 Note: Tracked the command process and its children")
print("=" * 60)
Expand Down
40 changes: 40 additions & 0 deletions tests/cli/test_monitor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from types import SimpleNamespace

import pytest
Expand All @@ -11,6 +12,7 @@ def __init__(self, *args, **kwargs):
self.kwargs = kwargs
self.stopped = 0
self._conf = {"output_file": "emissions.csv"}
self._output_handlers = [SimpleNamespace(save_file_path="emissions.csv")]

def start(self):
return None
Expand Down Expand Up @@ -178,3 +180,41 @@ def kill(self):
assert exc_info.value.exit_code == 130
assert process_info["terminated"] == 1
assert process_info["killed"] == 1


def _run_and_capture(monkeypatch, capsys, handlers):
class FakePopen:
def __init__(self, command, text=True):
pass

def wait(self):
return 0

class FakeTrackerWithHandlers(FakeTracker):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._output_handlers = handlers

_patch_trackers(monkeypatch, online_cls=FakeTrackerWithHandlers)
monkeypatch.setattr(monitor_module.subprocess, "Popen", FakePopen)

with pytest.raises(typer.Exit):
monitor_module.run_and_monitor(SimpleNamespace(args=["echo", "hi"]))

# rich wraps long lines to the terminal width, so strip all whitespace
return "".join(capsys.readouterr().out.split())


def test_run_and_monitor_reports_output_dir(monkeypatch, capsys, tmp_path):
save_file_path = os.path.join(str(tmp_path), "emissions.csv")
out = _run_and_capture(
monkeypatch, capsys, [SimpleNamespace(save_file_path=save_file_path)]
)

assert f"Savedto:{save_file_path}" in out


def test_run_and_monitor_reports_no_path_without_file_output(monkeypatch, capsys):
out = _run_and_capture(monkeypatch, capsys, [SimpleNamespace()])

assert "Savedto:" not in out
Loading