Skip to content

Instantly share code, notes, and snippets.

@chilcote
Last active October 6, 2022 16:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chilcote/ae63ec18149260028cb03ff81e351d58 to your computer and use it in GitHub Desktop.
Save chilcote/ae63ec18149260028cb03ff81e351d58 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
'''
Display CPU usage for a given process
emoji ref: https://github.com/sheagcraig/Spruce/blob/master/spruce.py
'''
import subprocess
import time
import argparse
def get_emoji(percentage):
"""Return one of 10 possible emojis depending on percentage.
Args:
percentage: A float between 0 and 1.
Returns:
An emoji string.
"""
level = [
"πŸ•πŸŽ‰", # Pizza Party
"πŸ»πŸŽ‰", # Beer Party
"🚨", # Klaxon
"πŸ©πŸ’¨", # Poodle Fart
"🌡", # Cactus
"πŸ’€", # Skull
"πŸ‘»", # Ghost
"πŸ’£", # The Bomb
"πŸπŸ›©", # Snakes on a Plane
"πŸ”₯", # Fire
"πŸ”₯πŸ”₯πŸ”₯" * 3] # Fire Fire Fire
if percentage <= 100:
return level[int(percentage / 10)]
elif 100 < percentage < 200:
return level[9]
else:
return level[10]
def get_process(p):
cmd = ['ps', 'axcopid,command,%cpu']
output = subprocess.check_output(cmd)
for line in output.splitlines():
if p in line:
return line.split()
return None, None, None
def main():
'''Sampling CPU usage by a process'''
parser = argparse.ArgumentParser(
description='Check CPU usage for a process')
parser.add_argument('-s', '--seconds', type=int,
help='how long to run the sample')
parser.add_argument('-p', '--process',
help='the process to check')
args = parser.parse_args()
seconds = args.seconds if args.seconds else 30
process = args.process if args.process else 'sentineld'
process+=' '
pid, proc, _ = get_process(process.encode())
if not pid:
print('No process by the name of %s found. Aborting.' % process.strip())
exit(0)
print('Press ctrl-c to stop this madness\n')
print('PID: %s' % pid)
print('Process: %s\n' % proc)
l = []
timer = 0
while timer < seconds:
try:
proc, name, percent = get_process(process.encode())
l.append(float(percent))
print('Percent CPU: %0.2f %-10s' % (l[-1], get_emoji(l[-1])))
time.sleep(1)
timer+=1
except KeyboardInterrupt:
break
avg = sum(l)/len(l)
print('-' * 19)
print('Average CPU: %0.2f' % avg)
print('Maximum CPU: %0.2f' % sorted(l)[-1])
print('Minumum CPU: %0.2f' % sorted(l)[0])
if avg > 200:
msg = '\nHoly Crap! Step away from your computer!'
if avg > 100:
msg = '\nIt\'s getting hot in here! ' + \
'You might wanna buy a fan for your desk!'
elif avg > 30:
msg = '\nSomeone sure is hungry for CPUs!'
elif avg > 10:
msg = '\nAt least you don\'t need to buy a hot pot!'
else:
msg = '\nNothing to see here. Move along, folks.'
print('%s %s' % (msg, get_emoji(avg)))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment