System uptime in Python, a better way
Published
I've been working on a system monitoring tool which needs determine whether the uptime of a Linux slave machine has changed since it last reported in. I looked through Python's online documentation and it turns out that there isn't a function among the standard modules for doing this (not even in the handy os module).
I did some searching around to see how people were getting the uptime of a host in Python and a surprising number of people advocate launching a subprocess and calling Linux's uptime command, then parsing the output. But there's a much better way!
Anybody familiar with Unix or Linux will know that the /proc directory is full of goodies (man proc if you don't believe me), including the file /proc/uptime which, as you might imagine, contains the current system uptime, along with information about how many seconds the CPU has been idle since the machine was turned on.
$ cat /proc/uptime 3112921.90 9475498.57 $
With this knowledge we can put together a script to read and display the current system uptime:
#!/usr/bin/python
from datetime import timedelta
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_string = str(timedelta(seconds = uptime_seconds))
print(uptime_string)
Hey presto! That'll get the current uptime since the epoch out of /proc/uptime and turn it into a human-readable form using the really handy timedelta function which I recently came across. Seems almost too easy, doesn't it?
The output looks something like this:
$ ./uptime.py 35 days, 23:06:35.530000 $
I
Python.