Loading

uptime.py

  1. #!/usr/bin/python
  2. import os
  3.  
  4. #----------------------------------------
  5. # Gives a human-readable uptime string
  6. def uptime():
  7.  
  8.      try:
  9.          f = open( "/proc/uptime" )
  10.          contents = f.read().split()
  11.          f.close()
  12.      except:
  13.         return "Cannot open uptime file: /proc/uptime"
  14.  
  15.      total_seconds = float(contents[0])
  16.  
  17.      # Helper vars:
  18.      MINUTE  = 60
  19.      HOUR    = MINUTE * 60
  20.      DAY     = HOUR * 24
  21.  
  22.      # Get the days, hours, etc:
  23.      days    = int( total_seconds / DAY )
  24.      hours   = int( ( total_seconds % DAY ) / HOUR )
  25.      minutes = int( ( total_seconds % HOUR ) / MINUTE )
  26.      seconds = int( total_seconds % MINUTE )
  27.  
  28.      # Build up the pretty string (like this: "N days, N hours, N minutes, N seconds")
  29.      string = ""
  30.      if days > 0:
  31.          string += str(days) + " " + (days == 1 and "day" or "days" ) + ", "
  32.      if len(string) > 0 or hours > 0:
  33.          string += str(hours) + " " + (hours == 1 and "hour" or "hours" ) + ", "
  34.      if len(string) > 0 or minutes > 0:
  35.          string += str(minutes) + " " + (minutes == 1 and "minute" or "minutes" ) + ", "
  36.      string += str(seconds) + " " + (seconds == 1 and "second" or "seconds" )
  37.  
  38.      return string;
  39.  
  40. print "The system uptime is:", uptime()

Comments