summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorGiampaolo Rodola <g.rodola@gmail.com>2019-04-05 17:44:45 +0200
committerGiampaolo Rodola <g.rodola@gmail.com>2019-04-05 17:44:45 +0200
commit90135fa7fa63a0eadd318374d455c04565ce1d8e (patch)
tree97b0b608c2676559a74d90fe21b4e3d149c80e2f /scripts
parentb24c552bc0a18ba894ae39907167e903dcafa924 (diff)
downloadpsutil-90135fa7fa63a0eadd318374d455c04565ce1d8e.tar.gz
move bytes2human() into psutil._common and reused it from scripts dir
Diffstat (limited to 'scripts')
-rwxr-xr-xscripts/disk_usage.py18
-rwxr-xr-xscripts/ifconfig.py19
-rwxr-xr-xscripts/internal/download_exes.py19
-rwxr-xr-xscripts/iotop.py21
-rwxr-xr-xscripts/meminfo.py18
-rwxr-xr-xscripts/nettop.py21
-rwxr-xr-xscripts/procinfo.py25
-rwxr-xr-xscripts/ps.py90
-rwxr-xr-xscripts/top.py62
9 files changed, 79 insertions, 214 deletions
diff --git a/scripts/disk_usage.py b/scripts/disk_usage.py
index 37f4da0c..1860401f 100755
--- a/scripts/disk_usage.py
+++ b/scripts/disk_usage.py
@@ -18,23 +18,7 @@ Device Total Used Free Use % Type Mount
import sys
import os
import psutil
-
-
-def bytes2human(n):
- # http://code.activestate.com/recipes/578019
- # >>> bytes2human(10000)
- # '9.8K'
- # >>> bytes2human(100001221)
- # '95.4M'
- 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 "%sB" % n
+from psutil._common import bytes2human
def main():
diff --git a/scripts/ifconfig.py b/scripts/ifconfig.py
index e2a9ce53..ad62a44f 100755
--- a/scripts/ifconfig.py
+++ b/scripts/ifconfig.py
@@ -47,6 +47,7 @@ from __future__ import print_function
import socket
import psutil
+from psutil._common import bytes2human
af_map = {
@@ -62,24 +63,6 @@ duplex_map = {
}
-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 '%.2f%s' % (value, s)
- return '%.2fB' % (n)
-
-
def main():
stats = psutil.net_if_stats()
io_counters = psutil.net_io_counters(pernic=True)
diff --git a/scripts/internal/download_exes.py b/scripts/internal/download_exes.py
index 41e303f8..1b72a177 100755
--- a/scripts/internal/download_exes.py
+++ b/scripts/internal/download_exes.py
@@ -21,6 +21,7 @@ import requests
import shutil
from psutil import __version__ as PSUTIL_VERSION
+from psutil._common import bytes2human
from scriptutils import printerr, exit
@@ -50,24 +51,6 @@ def safe_rmtree(path):
shutil.rmtree(path, onerror=onerror)
-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 '%.2f %s' % (value, s)
- return '%.2f B' % (n)
-
-
def download_file(url):
local_fname = url.split('/')[-1]
local_fname = os.path.join('dist', local_fname)
diff --git a/scripts/iotop.py b/scripts/iotop.py
index dabe957b..6a5d3fa9 100755
--- a/scripts/iotop.py
+++ b/scripts/iotop.py
@@ -39,9 +39,9 @@ except ImportError:
sys.exit('platform not supported')
import psutil
+from psutil._common import bytes2human
-# --- curses stuff
def tear_down():
win.keypad(0)
curses.nocbreak()
@@ -70,25 +70,6 @@ def print_line(line, highlight=False):
raise
else:
lineno += 1
-# --- /curses stuff
-
-
-def bytes2human(n):
- """
- >>> bytes2human(10000)
- '9.8 K/s'
- >>> bytes2human(100001221)
- '95.4 M/s'
- """
- 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 '%.2f %s/s' % (value, s)
- return '%.2f B/s' % (n)
def poll(interval):
diff --git a/scripts/meminfo.py b/scripts/meminfo.py
index 88c3a937..0b15ff2b 100755
--- a/scripts/meminfo.py
+++ b/scripts/meminfo.py
@@ -31,23 +31,7 @@ Sout : 0B
"""
import psutil
-
-
-def bytes2human(n):
- # http://code.activestate.com/recipes/578019
- # >>> bytes2human(10000)
- # '9.8K'
- # >>> bytes2human(100001221)
- # '95.4M'
- 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 "%sB" % n
+from psutil._common import bytes2human
def pprint_ntuple(nt):
diff --git a/scripts/nettop.py b/scripts/nettop.py
index e13903c1..45b8879f 100755
--- a/scripts/nettop.py
+++ b/scripts/nettop.py
@@ -40,9 +40,9 @@ except ImportError:
sys.exit('platform not supported')
import psutil
+from psutil._common import bytes2human
-# --- curses stuff
def tear_down():
win.keypad(0)
curses.nocbreak()
@@ -71,25 +71,6 @@ def print_line(line, highlight=False):
raise
else:
lineno += 1
-# --- curses stuff
-
-
-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 '%.2f %s' % (value, s)
- return '%.2f B' % (n)
def poll(interval):
diff --git a/scripts/procinfo.py b/scripts/procinfo.py
index 54205de3..161b5057 100755
--- a/scripts/procinfo.py
+++ b/scripts/procinfo.py
@@ -91,6 +91,7 @@ import socket
import sys
import psutil
+from psutil._common import bytes2human
ACCESS_DENIED = ''
@@ -115,18 +116,6 @@ RLIMITS_MAP = {
}
-def convert_bytes(n):
- 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 "%sB" % n
-
-
def print_(a, b):
if sys.stdout.isatty() and psutil.POSIX:
fmt = '\x1b[1;32m%-13s\x1b[0m %s' % (a, b)
@@ -135,13 +124,13 @@ def print_(a, b):
print(fmt)
-def str_ntuple(nt, bytes2human=False):
+def str_ntuple(nt, convert_bytes=False):
if nt == ACCESS_DENIED:
return ""
- if not bytes2human:
+ if not convert_bytes:
return ", ".join(["%s=%s" % (x, getattr(nt, x)) for x in nt._fields])
else:
- return ", ".join(["%s=%s" % (x, convert_bytes(getattr(nt, x)))
+ return ", ".join(["%s=%s" % (x, bytes2human(getattr(nt, x)))
for x in nt._fields])
@@ -193,7 +182,7 @@ def run(pid, verbose=False):
if hasattr(proc, "cpu_num"):
print_("cpu-num", pinfo["cpu_num"])
- print_('memory', str_ntuple(pinfo['memory_info'], bytes2human=True))
+ print_('memory', str_ntuple(pinfo['memory_info'], convert_bytes=True))
print_('memory %', round(pinfo['memory_percent'], 2))
print_('user', pinfo['username'])
if psutil.POSIX:
@@ -224,7 +213,7 @@ def run(pid, verbose=False):
print_('num-handles', pinfo['num_handles'])
if 'io_counters' in pinfo:
- print_('I/O', str_ntuple(pinfo['io_counters'], bytes2human=True))
+ print_('I/O', str_ntuple(pinfo['io_counters'], convert_bytes=True))
if 'num_ctx_switches' in pinfo:
print_("ctx-switches", str_ntuple(pinfo['num_ctx_switches']))
if pinfo['children']:
@@ -322,7 +311,7 @@ def run(pid, verbose=False):
if not verbose and i >= NON_VERBOSE_ITERATIONS:
print_("", "[...]")
break
- print_("", template % (convert_bytes(region.rss), region.path))
+ print_("", template % (bytes2human(region.rss), region.path))
def main(argv=None):
diff --git a/scripts/ps.py b/scripts/ps.py
index b85790d6..bf28a462 100755
--- a/scripts/ps.py
+++ b/scripts/ps.py
@@ -16,6 +16,7 @@ import os
import time
import psutil
+from psutil._common import bytes2human
PROC_STATUSES_RAW = {
@@ -49,55 +50,52 @@ def main():
attrs.append('terminal')
print(templ % ("USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY",
"STAT", "START", "TIME", "COMMAND"))
- for p in psutil.process_iter():
- try:
- pinfo = p.as_dict(attrs, ad_value='')
- except psutil.NoSuchProcess:
- pass
+ for p in psutil.process_iter(attrs, ad_value=''):
+ pinfo = p.info
+ if pinfo['create_time']:
+ ctime = datetime.datetime.fromtimestamp(pinfo['create_time'])
+ if ctime.date() == today_day:
+ ctime = ctime.strftime("%H:%M")
+ else:
+ ctime = ctime.strftime("%b%d")
else:
- if pinfo['create_time']:
- ctime = datetime.datetime.fromtimestamp(pinfo['create_time'])
- if ctime.date() == today_day:
- ctime = ctime.strftime("%H:%M")
+ ctime = ''
+ cputime = time.strftime("%M:%S",
+ time.localtime(sum(pinfo['cpu_times'])))
+ try:
+ user = p.username()
+ except KeyError:
+ if psutil.POSIX:
+ if pinfo['uids']:
+ user = str(pinfo['uids'].real)
else:
- ctime = ctime.strftime("%b%d")
+ user = ''
else:
- ctime = ''
- cputime = time.strftime("%M:%S",
- time.localtime(sum(pinfo['cpu_times'])))
- try:
- user = p.username()
- except KeyError:
- if os.name == 'posix':
- if pinfo['uids']:
- user = str(pinfo['uids'].real)
- else:
- user = ''
- else:
- raise
- except psutil.Error:
- user = ''
- if os.name == 'nt' and '\\' in user:
- user = user.split('\\')[1]
- vms = pinfo['memory_info'] and \
- int(pinfo['memory_info'].vms / 1024) or '?'
- rss = pinfo['memory_info'] and \
- int(pinfo['memory_info'].rss / 1024) or '?'
- memp = pinfo['memory_percent'] and \
- round(pinfo['memory_percent'], 1) or '?'
- status = PROC_STATUSES_RAW.get(pinfo['status'], pinfo['status'])
- print(templ % (
- user[:10],
- pinfo['pid'],
- pinfo['cpu_percent'],
- memp,
- vms,
- rss,
- pinfo.get('terminal', '') or '?',
- status,
- ctime,
- cputime,
- pinfo['name'].strip() or '?'))
+ raise
+ except psutil.Error:
+ user = ''
+ if psutil.WINDOWS and '\\' in user:
+ user = user.split('\\')[1]
+ vms = bytes2human(pinfo['memory_info'].vms) if \
+ pinfo['memory_info'] is not None else ''
+ rss = bytes2human(pinfo['memory_info'].rss) if \
+ pinfo['memory_info'] is not None else ''
+ memp = round(pinfo['memory_percent'], 1) if \
+ pinfo['memory_percent'] is not None else ''
+
+ status = PROC_STATUSES_RAW.get(pinfo['status'], pinfo['status'])
+ print(templ % (
+ user[:10],
+ pinfo['pid'],
+ pinfo['cpu_percent'],
+ memp,
+ vms,
+ rss,
+ pinfo.get('terminal', '') or '',
+ status,
+ ctime,
+ cputime,
+ pinfo['name'].strip() or '?'))
if __name__ == '__main__':
diff --git a/scripts/top.py b/scripts/top.py
index 70dbf6c9..16f6da3b 100755
--- a/scripts/top.py
+++ b/scripts/top.py
@@ -10,27 +10,26 @@ A clone of top / htop.
Author: Giampaolo Rodola' <g.rodola@gmail.com>
$ python scripts/top.py
- CPU0 [| ] 4.9%
- CPU1 [||| ] 7.8%
- CPU2 [ ] 2.0%
- CPU3 [||||| ] 13.9%
- Mem [||||||||||||||||||| ] 49.8% 4920M / 9888M
- Swap [ ] 0.0% 0M / 0M
- Processes: 287 (running=1, sleeping=286, zombie=1)
- Load average: 0.34 0.54 0.46 Uptime: 3 days, 10:16:37
-
-PID USER NI VIRT RES CPU% MEM% TIME+ NAME
-------------------------------------------------------------
-989 giampaol 0 66M 12M 7.4 0.1 0:00.61 python
-2083 root 0 506M 159M 6.5 1.6 0:29.26 Xorg
-4503 giampaol 0 599M 25M 6.5 0.3 3:32.60 gnome-terminal
-3868 giampaol 0 358M 8M 2.8 0.1 23:12.60 pulseaudio
-3936 giampaol 0 1G 111M 2.8 1.1 33:41.67 compiz
-4401 giampaol 0 536M 141M 2.8 1.4 35:42.73 skype
-4047 giampaol 0 743M 76M 1.8 0.8 42:03.33 unity-panel-service
-13155 giampaol 0 1G 280M 1.8 2.8 41:57.34 chrome
-10 root 0 0B 0B 0.9 0.0 4:01.81 rcu_sched
-339 giampaol 0 1G 113M 0.9 1.1 8:15.73 chrome
+ CPU0 [|||| ] 10.9%
+ CPU1 [||||| ] 13.1%
+ CPU2 [||||| ] 12.8%
+ CPU3 [|||| ] 11.5%
+ Mem [||||||||||||||||||||||||||||| ] 73.0% 11017M / 15936M
+ Swap [ ] 1.3% 276M / 20467M
+ Processes: 347 (sleeping=273, running=1, idle=73)
+ Load average: 1.10 1.28 1.34 Uptime: 8 days, 21:15:40
+
+PID USER NI VIRT RES CPU% MEM% TIME+ NAME
+5368 giampaol 0 7.2G 4.3G 41.8 27.7 56:34.18 VirtualBox
+24976 giampaol 0 2.1G 487.2M 18.7 3.1 22:05.16 Web Content
+22731 giampaol 0 3.2G 596.2M 11.6 3.7 35:04.90 firefox
+1202 root 0 807.4M 288.5M 10.6 1.8 12:22.12 Xorg
+22811 giampaol 0 2.8G 741.8M 9.0 4.7 2:26.61 Web Content
+2590 giampaol 0 2.3G 579.4M 5.5 3.6 28:02.70 compiz
+22990 giampaol 0 3.0G 1.2G 4.2 7.6 4:30.32 Web Content
+18412 giampaol 0 90.1M 14.5M 3.5 0.1 0:00.26 python3
+26971 netdata 0 20.8M 3.9M 2.9 0.0 3:17.14 apps.plugin
+2421 giampaol 0 3.3G 36.9M 2.3 0.2 57:14.21 pulseaudio
...
"""
@@ -45,6 +44,7 @@ except ImportError:
sys.exit('platform not supported')
import psutil
+from psutil._common import bytes2human
# --- curses stuff
@@ -81,24 +81,6 @@ def print_line(line, highlight=False):
# --- /curses stuff
-def bytes2human(n):
- """
- >>> bytes2human(10000)
- '9K'
- >>> bytes2human(100001221)
- '95M'
- """
- 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 = int(float(n) / prefix[s])
- return '%s%s' % (value, s)
- return "%sB" % n
-
-
def poll(interval):
# sleep some time
time.sleep(interval)
@@ -178,7 +160,7 @@ def print_header(procs_status, num_procs):
def refresh_window(procs, procs_status):
"""Print results on screen by using curses."""
curses.endwin()
- templ = "%-6s %-8s %4s %5s %5s %6s %4s %9s %2s"
+ templ = "%-6s %-8s %4s %6s %6s %5s %5s %9s %2s"
win.erase()
header = templ % ("PID", "USER", "NI", "VIRT", "RES", "CPU%", "MEM%",
"TIME+", "NAME")