Skip to content

Instantly share code, notes, and snippets.

@esirK
Last active August 15, 2021 07:50
Show Gist options
  • Save esirK/e456bc6701695ad9d1d51f3cc3bf5ec9 to your computer and use it in GitHub Desktop.
Save esirK/e456bc6701695ad9d1d51f3cc3bf5ec9 to your computer and use it in GitHub Desktop.
import shutil
import subprocess
statistics = {}
# Top command on mac displays and updates sorted information about processes.
top_command = subprocess.run(['top', '-l 1', '-n 0'], stdout=subprocess.PIPE).stdout.decode('utf-8').split('\n')
# Disk usage
# Get total disk size, used disk space, and free disk
total, used, free = shutil.disk_usage("/")
# Number of Read and write operations
# from the top command, the read written result will be as follows
# 'Disks: XXXXXX/xxG read, XXXX/xxG written.'
# we thus need to extract the read and written from this.
read_written = top_command[9].split(':')[1].split(',')
read = read_written[0].split(' ')[1]
written = read_written[1].split(' ')[1]
statistics['disk'] = dict(
{
'total_disk_space': round(total / 1024 ** 3, 1),
'used_disk_space': round(used / 1024 ** 3, 1),
'free_disk_space': round(free / 1024 ** 3, 1),
'read_write': {
'read': read,
'written': written
}
}
)
@PrashanthAdurugatla
Copy link

For ubuntu machines, -l option doesn't support on top command. It throws this error
top: unknown option 'l' Usage: top -hv | -bcHiOSs -d secs -n max -u|U user -p pid(s) -o field -w [cols]
Can you know hoe to fix this?

@esirK
Copy link
Author

esirK commented Aug 15, 2021

Hey @PrashanthAdurugatla
Sorry about that. The script was created with mac-os in mind. I'll look for a solution and update it to work for ubuntu.
In the meantime, you can comment out lines 8, 19, 20, 21, and 28-31

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment