Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
88 lines (69 loc) · 2.7 KB
/
Copy pathcli.py
File metadata and controls
88 lines (69 loc) · 2.7 KB
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
import argparse
import sys
import proc_reader as pr
def format_kb(kb):
"""Pretty-print a kB value as MB/GB depending on magnitude."""
if kb >= 1024 * 1024:
return f"{kb / (1024 * 1024):.2f} GB"
if kb >= 1024:
return f"{kb / 1024:.1f} MB"
return f"{kb} kB"
def format_uptime(seconds):
seconds = int(seconds)
h, rem = divmod(seconds, 3600)
m, s = divmod(rem, 60)
return f"{h}h {m}m {s}s"
def cmd_mem(_args):
mem = pr.get_meminfo()
print("System memory (from /proc/meminfo)")
print("-" * 40)
print(f" Total: {format_kb(mem['total_kb'])}")
print(f" Used: {format_kb(mem['used_kb'])} ({mem['used_percent']}%)")
print(f" Free: {format_kb(mem['free_kb'])}")
print(f" Cached: {format_kb(mem['cached_kb'])}")
print(f" Available: {format_kb(mem['available_kb'])}")
def cmd_list(_args):
print(f"{'PID':>7} {'STATE':<24} {'RSS':>10} NAME")
print("-" * 60)
for pid in pr.list_pids():
try:
info = pr.get_status(pid)
except (pr.ProcessNotFound, PermissionError):
# Process exited between listing and reading, or needs root.
continue
print(
f"{info['pid']:>7} {info['state']:<24} "
f"{format_kb(info['vm_rss_kb']):>10} {info['name']}"
)
def cmd_process(args):
try:
info = pr.get_process_info(args.pid)
except pr.ProcessNotFound:
print(f"No such process: {args.pid}", file=sys.stderr)
sys.exit(1)
except PermissionError:
print(f"Permission denied reading PID {args.pid} (try sudo)", file=sys.stderr)
sys.exit(1)
print(f"Process {info['pid']} ({info['name']})")
print("-" * 40)
print(f" Command: {info['cmdline']}")
print(f" State: {info['state']}")
print(f" Parent: {info['ppid']}")
print(f" Threads: {info['threads']}")
print(f" Uptime: {format_uptime(info['uptime_seconds'])}")
print(f" VmSize: {format_kb(info['vm_size_kb'])} (virtual)")
print(f" VmRSS: {format_kb(info['vm_rss_kb'])} (resident)")
def main():
parser = argparse.ArgumentParser(
description="Inspect Linux process and memory stats via /proc directly."
)
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("mem", help="Show system-wide memory summary").set_defaults(func=cmd_mem)
sub.add_parser("list", help="List all running processes").set_defaults(func=cmd_list)
p_process = sub.add_parser("process", help="Show details for one PID")
p_process.add_argument("pid", type=int)
p_process.set_defaults(func=cmd_process)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()