Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting system status in python

Is there any way to get system status in python, for example the amount of memory free, processes that are running, cpu load and so on. I know on linux I can get this from the /proc directory, but I would like to do this on unix and windows as well.

like image 414
Botto Avatar asked Aug 18 '09 21:08

Botto


2 Answers

I don't know of any such library/ package that currently supports both Linux and Windows. There's libstatgrab which doesn't seem to be very actively developed (it already supports a decent variety of Unix platforms though) and the very active PSI (Python System Information) which works on AIX, Linux, SunOS and Darwin. Both projects aim at having Windows support sometime in the future. Good luck.

like image 154
Gerald Senarclens de Grancy Avatar answered Oct 23 '22 01:10

Gerald Senarclens de Grancy


I don't think there is a cross-platform library for that yet (there definitely should be one though)

I can however provide you with one snippet I used to get the current CPU load from /proc/stat under Linux:

Edit: replaced horrible undocumented code with slightly more pythonic and documented code

import time

INTERVAL = 0.1

def getTimeList():
    """
    Fetches a list of time units the cpu has spent in various modes
    Detailed explanation at http://www.linuxhowtos.org/System/procstat.htm
    """
    cpuStats = file("/proc/stat", "r").readline()
    columns = cpuStats.replace("cpu", "").split(" ")
    return map(int, filter(None, columns))

def deltaTime(interval):
    """
    Returns the difference of the cpu statistics returned by getTimeList
    that occurred in the given time delta
    """
    timeList1 = getTimeList()
    time.sleep(interval)
    timeList2 = getTimeList()
    return [(t2-t1) for t1, t2 in zip(timeList1, timeList2)]

def getCpuLoad():
    """
    Returns the cpu load as a value from the interval [0.0, 1.0]
    """
    dt = list(deltaTime(INTERVAL))
    idle_time = float(dt[3])
    total_time = sum(dt)
    load = 1-(idle_time/total_time)
    return load


while True:
    print "CPU usage=%.2f%%" % (getCpuLoad()*100.0)
    time.sleep(0.1)
like image 22
Otto Allmendinger Avatar answered Oct 23 '22 00:10

Otto Allmendinger