I like to use these commands to see my memory usage on my servers:
ps -u $USERNAME -o pid,rss,command | awk '{print $0}{sum+=$2} END {print "Total", sum}'
What would be the best way to collect that total sum in a Python script? I had a look as psutil but that module only collects global memory information and there is no way to filter it down by user.
It's pretty simple using psutil
. You can just iterate over all processes, select the ones that are owned by you and sum the memory returned by memory_info()
.
import psutil
import getpass
user = getpass.getuser()
total = sum(p.memory_info()[0] for p in psutil.process_iter()
if p.username() == user)
print('Total memory usage in bytes: ', total)