GeekTool CPU Script

If you don’t know what GeekTool is go here.
It is very likely you’ll find it useful. If you use Tiger, use this version that fixes a lot of issues.

GeekTool allows you to put a lot of interesting informations on the desktop. You can “print” logfiles on the desktop or you can put there pictures or, and that is what is interesting, put the output of a chosen command.
For example I put a random fortune on the desktop. It easier to do download GeekTool and do it than reading an explanation.

An interesting feature that is in the documentation (so it’s something you probably wouldn’t read) is that scripts/commands placed in “~/Library/Application Support/GeekTool Scripts” need not to be specified with full path. So we will put the script “cpuload.py” in that directory and we will refer to it with “cpuload.py”

And now the script:


    #!/usr/bin/python
    # -*- coding: utf-8 -*-

    import os

    class command(object):
        def __init__(self, c):
            self._command = c
            fi, foe = os.popen4(self._command)
            fi.close()
            self.out = list([line.strip() for line in foe])
            foe.close() 

    def cpu_load(string_list):
        # a bit functional... not pythonic at all
        return sum(map(lambda l: float(l.split()[2]), 
            string_list), 0)

    def main():
        ulist = command("ps -ux").out[1:]
        slist = command("ps -aux").out[1:]
        print "System CPU: ", cpu_load(slist), "%"
        print "User CPU:   ", cpu_load(ulist), "%"

    if __name__ == "__main__":
        main()

Class “command” is a stripped down version of a class I’m writing for another project. I also think that any script you write should be executable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: