Python: Uptime script
Saturday, November 19th, 2005I’ve been writing Python for a grand total of 2 days. I recently wrote a little Python script to print a Linx or UNIX system’s uptime. This took about 10 minutes to write, so I was pretty pleased. It even runs well on a 75MHz Busybox embedded Linux system. Check it out:
#!/usr/bin/python
import os
#----------------------------------------
# Gives a human-readable uptime string
def uptime():
try:
f = open( "/proc/uptime" )
contents = f.read().split()
f.close()
except:
return "Cannot open uptime file: /proc/uptime"
total_seconds = float(contents[0])
# Helper vars:
MINUTE = 60
HOUR = MINUTE * 60
DAY = HOUR * 24
# Get the days, hours, etc:
days = int( total_seconds / DAY )
hours = int( ( total_seconds % DAY ) / HOUR )
minutes = int( ( total_seconds % HOUR ) / MINUTE )
seconds = int( total_seconds % MINUTE )
# Build up the pretty string (like this: "N days, N hours, N minutes, N seconds")
string = ""
if days > 0:
string += str(days) + " " + (days == 1 and "day" or "days" ) + ", "
if len(string) > 0 or hours > 0:
string += str(hours) + " " + (hours == 1 and "hour" or "hours" ) + ", "
if len(string) > 0 or minutes > 0:
string += str(minutes) + " " + (minutes == 1 and "minute" or "minutes" ) + ", "
string += str(seconds) + " " + (seconds == 1 and "second" or "seconds" )
return string;
print "The system uptime is:", uptime()
One interesting thing about this script is its emulation of the C ternary operator using Python’s short-circuited “and” operator. Notice this bit:
(days == 1 and "day" or "days" )
Python doesn’t have the C-style ternary operator:
(days == 1 ? "day" : "days")
So the short-circuited “and” is a decent alternative. Instead of ignorantly printing “1 days”, this code will actually print “1 day” and “2 days” like it should.