Skip to content

Commit

Permalink
fix #1474: fix formatting of psutil.tests() which mimicks 'ps aux' ou…
Browse files Browse the repository at this point in the history
…tput
  • Loading branch information
giampaolo committed Apr 5, 2019
1 parent d4cbce0 commit 275df44
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
1 change: 1 addition & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
exist. (patch by Cedric Lamoriniere)
- 1471_: [SunOS] Process name() and cmdline() can return SystemError. (patch
by Daniel Beer)
- 1474_: fix formatting of psutil.tests() which mimicks 'ps aux' output.
- 1475_: [Windows] OSError.winerror attribute wasn't properly checked resuling
in WindowsError being raised instead of AccessDenied.
- 1477_: [Windows] wrong or absent error handling for private NTSTATUS Windows
Expand Down
39 changes: 29 additions & 10 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2441,16 +2441,33 @@ def test(): # pragma: no cover
"""List info of all currently running processes emulating ps aux
output.
"""
def bytes2human(n):
"""
>>> bytes2human(10000)
'9.8 K'
>>> bytes2human(100001221)
'95.4 M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return '%.1fB' % (n)

today_day = datetime.date.today()
templ = "%-10s %5s %4s %7s %7s %-13s %5s %7s %s"
templ = "%-10s %6s %5s %8s %8s %12s %5s %7s %s"
attrs = ['pid', 'memory_percent', 'name', 'cpu_times', 'create_time',
'memory_info']
if POSIX:
attrs.append('uids')
attrs.append('terminal')
print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "TTY", "START", "TIME",
"COMMAND"))
for p in process_iter(attrs=attrs, ad_value=''):
for p in process_iter(attrs=attrs, ad_value=None):
if p.info['create_time']:
ctime = datetime.datetime.fromtimestamp(p.info['create_time'])
if ctime.date() == today_day:
Expand All @@ -2462,24 +2479,26 @@ def test(): # pragma: no cover
cputime = time.strftime("%M:%S",
time.localtime(sum(p.info['cpu_times'])))
try:
user = p.username()
user = p.username()[:9]
except Error:
user = ''
if WINDOWS and '\\' in user:
user = user.split('\\')[1]
vms = p.info['memory_info'] and \
int(p.info['memory_info'].vms / 1024) or '?'
rss = p.info['memory_info'] and \
int(p.info['memory_info'].rss / 1024) or '?'
memp = p.info['memory_percent'] and \
round(p.info['memory_percent'], 1) or '?'

vms = bytes2human(p.info['memory_info'].vms) if \
p.info['memory_info'] is not None else ''
rss = bytes2human(p.info['memory_info'].rss) if \
p.info['memory_info'] is not None else ''
memp = round(p.info['memory_percent']) if \

This comment has been minimized.

Copy link
@embray

embray Apr 5, 2019

Contributor

This is now rounding even more aggressively than before, truncating to the nearest percent.

On my system ps aux at least shows tenths of a percent if a process's memory usage is at least that much:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
...
root      1010  0.2  0.1 1258076 39980 ?       Ssl   2018 629:50 /usr/bin/docker

This comment has been minimized.

Copy link
@giampaolo

giampaolo Apr 5, 2019

Author Owner

Oh right! Didn't noticed that. I rounded it to 1 digit in 3f67688.

This comment has been minimized.

Copy link
@embray

embray Apr 5, 2019

Contributor

Aha! You're already ahead of me. Let's just call it Giampaolo's time machine.

This comment has been minimized.

Copy link
@giampaolo

giampaolo Apr 5, 2019

Author Owner

=)
I should get more used to work in branches (and more slowly) instead of on master.

p.info['memory_percent'] is not None else ''

print(templ % (
user[:10],
p.info['pid'],
memp,
vms,
rss,
p.info.get('terminal', '') or '?',
p.info.get('terminal', '') or '',
ctime,
cputime,
p.info['name'].strip() or '?'))
Expand Down

0 comments on commit 275df44

Please sign in to comment.