Entry 53485

Process

   

Submitted by prashanth on Aug. 10, 2012 at 8:30 p.m.
Language: Python. Code size: 1.9 KB.

import os
import psutil
import sys
import pygal
# Data Structures(Dictionaries).

pid_actual = {}
pid_name = {}
user_table = {}

# This function does the arithmetic on the the PROC structure values and fills the dictionaries.
def getProcessDetails(pid):
    rss = 0
    shared_clean = 0
    p = psutil.Process(pid)
    pid_name[pid] = p.name
    procdata = p.get_memory_maps()
    for i in procdata:
        rss = rss + i.rss
        shared_clean = shared_clean + i.shared_clean
    pid_actual[pid] = rss - shared_clean

#The driver function -- segragates proceeses running based on the users who spawned them.
def main():
    list = psutil.get_pid_list()
    pie_chart = pygal.Pie()
    pie_chart.title = 'User Memory Usage Statistics'
    for pid in list:
        p = psutil.Process(pid)
        if p.username in user_table.keys():
            user_table[p.username].append(pid)
        else:
            plist = []
            plist.append(pid)
            user_table[p.username] = plist

    for user in user_table:
        plist = user_table[user]
        for pid in plist:
            getProcessDetails(pid)


# Final Printing

    for user in user_table:
        plist = user_table[user]
        total = 0
        #print user + " :"
        for pid in plist:
            total = total + pid_actual[pid]
        print user + "\t\t" + str(total/1024) + " KB"
        pie_chart.add(user, total)

    pie_chart.render_to_file('process_temp.svg')
    # Replace the Github urls to the local ones
    surl1 = 'https://raw.github.com/Kozea/pygal.js/master/svg.jquery.js'
    rurl1 = 'svg.jquery.js'
    surl2 = 'https://raw.github.com/Kozea/pygal.js/master/pygal-tooltips.js'
    rurl2 = 'pygal-tooltips.js'
    input = open('process_temp.svg')
    output = open('process.svg','w+')
    data = input.read()
    #print data
    data = data.replace(surl1,rurl1)
    data = data.replace(surl2,rurl2)
    #print data
    output.write(data)
if __name__ == "__main__":
    main()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).