Skip to content

Commit

Permalink
src/sage/doctest/util.py: support macOS if psutil is installed
Browse files Browse the repository at this point in the history
If psutil is installed (it usually will be, because ipython uses it),
we can use it to compute the cputime used by pexpect processes on
macOS. This is of course guarded by a try/except clause, and may not
always work, but is better than giving up immediately on macOS.
  • Loading branch information
orlitzky committed Oct 15, 2024
1 parent 9b26558 commit 5824aac
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/sage/doctest/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,14 +289,25 @@ def _quick_cputime(self, expect_objects):
S = s()
if S and S.is_running():
try:
# This will fail anywhere but linux/BSD, but
# there's no good cross-platform way to get the
# cputimes from pexpect interfaces without totally
# mucking up the doctests.
path = f"/proc/{S.pid()}/stat"
cputime += self._proc_stat_cpu_seconds(path)
except OSError:
# This will fail anywhere but linux/BSD, but
# there's no good cross-platform way to get the
# cputimes from pexpect interfaces without
# totally mucking up the doctests.
pass
# If we're on macOS, we can fall back to using
# psutil, but only if it's installed. It's usually
# installed as a transitive dependency (ipython
# needs it), but it isn't explicitly listed as
# a dependency of sagelib.
try:
from psutil import Process
cputime += sum(Process(S.pid()).cpu_times()[0:2])
except (ImportError, ValueError):
# ImportError: no psutil
# ValueError: invalid (e.g. negative) PID
pass

return cputime

Expand Down

0 comments on commit 5824aac

Please sign in to comment.