-
-
Save dunhamsteve/59f5e6b9a4bc69039853674dd8aac1c4 to your computer and use it in GitHub Desktop.
view process tree in ncdu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # Show hierarchical process memory usage via ncdu | |
| # I've updated this to lift children of zsh to make the top level more usefule to me. | |
| import json, subprocess, time, tempfile | |
| from collections import defaultdict | |
| from itertools import dropwhile | |
| def psize(s): return int(s[0:-1])*{'K':2**10, 'M':2**20, 'G':2**30}[s[-1]] | |
| def runcmd(cmd): | |
| res = subprocess.run(cmd.split(),capture_output=True,text=True) | |
| return list(dropwhile(lambda x: 'PID' not in x, res.stdout.splitlines()))[1:] | |
| byparent = defaultdict(list) | |
| for line in runcmd("top -l 1 -o mem -stats pid,ppid,mem,command"): | |
| parts = line.split(maxsplit=3) | |
| (pid,ppid,sz,cmd) = parts | |
| pid = int(parts[0]) | |
| ppid = int(parts[1]) | |
| if pid == 0: continue | |
| sz = psize(parts[2]) | |
| cmd = parts[3].strip() | |
| byparent[ppid].append((pid,sz,cmd)) | |
| # get process name, remove -c for full command line | |
| cmdline = {} | |
| for line in runcmd("ps -ceo pid,command"): | |
| (pid,cmd) = line.split(maxsplit=1) | |
| pid = int(pid) | |
| cmdline[pid] = cmd | |
| # reparent zsh children to the top | |
| if cmd.endswith('zsh'): | |
| byparent[1] += byparent[pid] | |
| byparent[pid] = [] | |
| def mktree(root): | |
| (pid, sz, name) = root | |
| name = cmdline.get(pid,name) | |
| node = {"name": name,"asize":sz,"dsize":sz} | |
| children = list(map(mktree,byparent[pid])) | |
| if len(children): | |
| return [node] + children | |
| return node | |
| data = [1,2,{"progname": "psdu", "progver": "1.0", "timestamp":int(time.time())}] + list(map(mktree, byparent[0])) | |
| with tempfile.NamedTemporaryFile(mode='w+', suffix='.json', delete=True) as temp: | |
| json.dump(data, temp) | |
| temp.flush() | |
| subprocess.run(['ncdu', '-f', temp.name], check=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment