-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprocsmem.py
executable file
·105 lines (89 loc) · 2.85 KB
/
procsmem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env python
"""Usage: psutil-procsmem [-h] [-s SORT]
Options:
-h --help # print this help
-s [SORT] --sort [SORT] # sort by column, either uss, pss, swap or pss
Description:
Show "real" (USS) memory usage about all (querable) processes.
"USS" (Unique Set Size) memory is probably the most representative metric
for determining how much memory is actually being used by a process as it
represents the amount of memory that would be freed if the process was
terminated right now.
This is similar to "smem" cmdline utility on Linux:
https://www.selenic.com/smem/
"""
from __future__ import print_function
import sys
from docopt import docopt
import psutil
from psutilcli import bytes2human
from psutilcli import color_cmdline
from psutilcli import exit
from psutilcli import warn
from psutilcli.compat import get_terminal_size
def main():
args = docopt(__doc__)
if not args['--sort']:
sort = 'uss'
else:
sort = args['--sort']
valid_params = ('uss', 'pss', 'swap', 'rss')
if sort not in valid_params:
exit("invalid sort parameter %r; choose between %s" % (
sort, ', '.join(valid_params)))
if not (psutil.LINUX or psutil.OSX or psutil.WINDOWS):
sys.exit("platform not supported")
ad_pids = []
procs = []
for p in psutil.process_iter():
with p.oneshot():
try:
info = p.as_dict(attrs=["pid", "cmdline", "username"])
info['mem'] = p.memory_full_info()._asdict()
except psutil.AccessDenied:
ad_pids.append(p.pid)
except psutil.NoSuchProcess:
pass
else:
procs.append(info)
procs.sort(key=lambda p: p['mem'][sort])
templ = "%-7s %7s %7s %7s %7s %7s %s"
print(templ % (
"PID",
"User",
"USS",
"PSS",
"Swap",
"RSS",
"Cmdline",
))
print("=" * 78)
for p in procs:
uss = p["mem"]["uss"]
if not uss:
continue
pss = p["mem"].get("pss", None)
swap = p["mem"].get("swap", None)
rss = p["mem"].get("rss", None)
uss = bytes2human(uss)
pss = bytes2human(pss) if pss is not None else ""
swap = bytes2human(swap) if swap is not None else ""
rss = bytes2human(rss) if rss is not None else ""
line = templ % (
p["pid"],
p["username"][:7],
uss,
pss,
swap,
rss,
""
)
size = get_terminal_size()[0] - len(line)
if size > 0:
line += color_cmdline(" ".join(p["cmdline"])[:size])
print(line)
if ad_pids:
warn("access denied for %s pids which were skipped; "
"try re-running as root" % (len(ad_pids)))
if __name__ == '__main__':
main()