Created
December 2, 2014 20:43
-
-
Save YellowSharkMT/d4ae1adeffafea7f32e5 to your computer and use it in GitHub Desktop.
Python shell script, displays memory usage for a user's processes. Also displays warning message if the usage is over a configurable amount.
This file contains 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/python | |
import subprocess | |
from datetime import datetime | |
import time | |
import sys | |
import itertools | |
# Configurable Values | |
MEM_LIMIT = 600000 | |
delay = 10 # polling interval for running the following command: | |
cmd = "ps -u CHANGEME_USERNAME -o rss,etime,pid,command | awk '{ SUM += $1 } END { print SUM }';" | |
# generic highlighting function, poached from somewhere / not my own | |
def hilite(string, status, bold): | |
if not sys.stdout.isatty(): | |
return string | |
attr = [] | |
if status is True: | |
# green | |
attr.append('32') | |
elif status is False: | |
# red | |
attr.append('31') | |
elif int(status) > 0: | |
attr.append(status) | |
if bold: | |
attr.append('1') | |
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) | |
# Creates the output, which is a combination of timestamp, memory usage, and warning msg if appropriate. | |
def make_output(text): | |
msgs = list() | |
msg = text[:-1] # trim off trailing \r\n | |
time_str = datetime.now().strftime("%Y-%d-%m, %H:%M:%S") | |
if int(msg) > MEM_LIMIT: | |
msgs.append(hilite("%s: *** Warning: mem usage is above %s ***" % (time_str, MEM_LIMIT), False, True)) | |
hl_msg = hilite(msg, '33', False) | |
msgs.append("%s: Current mem usage: %s" % (hilite(time_str, True, True), hl_msg)) | |
return "\r\n".join(msgs) | |
# Main uses iter() with a lambda, executing the `cmd` value via subprocess.Popen. Then it sleeps for the specified interval. | |
def main(): | |
for (out, err) in iter(lambda: subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True).communicate(), False): | |
print(make_output(out)) | |
time.sleep(delay) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment