Python: Uptime script
I'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:
PYTHON:
-
#!/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:
PYTHON:
-
(days == 1 and "day" or "days" )
Python doesn't have the C-style ternary operator:
C++:
-
(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.
April 16th, 2006 at 2:41 am
Nice script! I am going to use it in a script I am writing for my backup server at home (open Source of course). You saved me a lot of time.
January 28th, 2007 at 12:05 pm
Thanks for the nice hack with ternary operator, I was searching for it for a while now.
The script is nice to, though you might mention that, in order to be able to call it “uptime” instead of “python uptime” a line “#!/path/to/python/interpreter” should be added (it also took me a while to figure this out in the beginning).
January 28th, 2007 at 12:31 pm
This was meant as an example code snippet that others could use in their Python programs, not as a stand-alone script. For that purpose, I would just use the “uptime” command.
–Dave
September 6th, 2007 at 6:46 am
Thanks for the idea… I was just getting ready to call “uptime” via ssh to get the load average on a bunch of machines…. but after seeing this script I noticed that all I have to do is something like:
file = os.popen(’ssh machine_name “cat /proc/loadavg”‘)
contents = file.read().split()
print contents[0]
Which is much easier!
Friedmud