From 962cb9ad58ca3bc21b20130f435f8d507d931051 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 9 Jun 2023 15:37:14 +0200 Subject: [PATCH] bytes2human() is unable to print negative values (#2268) Signed-off-by: Giampaolo Rodola The bug: ``` >>> from psutil._common import bytes2human >>> bytes2human(212312454) 202.5M >>> bytes2human(-212312454) -212312454 ``` --- HISTORY.rst | 4 +++- docs/index.rst | 2 +- psutil/_common.py | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index c0cfe9d2d..6e1f065f4 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -7,8 +7,10 @@ XXXX-XX-XX - 2241_, [NetBSD]: can't compile On NetBSD 10.99.3/amd64. (patch by Thomas Klausner) -- 2266_: if `Process`_ class is passed a very high PID, raise `NoSuchProcess`_ +- 2266_: if `Process`_ class is passed a very high PID, raise `NoSuchProcess`_ instead of OverflowError. (patch by Xuehai Pan) +- 2268_: ``bytes2human()`` utility function was unable to properly represent + negative values. 5.9.5 ===== diff --git a/docs/index.rst b/docs/index.rst index 2bf050a11..31d5d7ef5 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -2544,7 +2544,7 @@ Bytes conversion for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): - if n >= prefix[s]: + if abs(n) >= prefix[s]: value = float(n) / prefix[s] return '%.1f%s' % (value, s) return "%sB" % n diff --git a/psutil/_common.py b/psutil/_common.py index 922867464..63792edbd 100644 --- a/psutil/_common.py +++ b/psutil/_common.py @@ -827,7 +827,7 @@ def bytes2human(n, format="%(value).1f%(symbol)s"): for i, s in enumerate(symbols[1:]): prefix[s] = 1 << (i + 1) * 10 for symbol in reversed(symbols[1:]): - if n >= prefix[symbol]: + if abs(n) >= prefix[symbol]: value = float(n) / prefix[symbol] return format % locals() return format % dict(symbol=symbols[0], value=n)