Saturday, 24 May 2014

Python Uptime Function

If you take a look in /proc/uptime you'll see two floating point numbers:

 mugwriter@interzone ~ $ cat /proc/uptime  
 1877.17 2961.48  

The first number is seconds since boot and the second number is how long the system has been idle for. I'm using a dual core system, so for every second that the system is idle the second number is incremented by two.

We can use the first number to write to calculate uptime and present it in a tidy fashion. Yes, I know there is always the "uptime" command, but there's no learning to be done just by using that. I'm trying to learn Python here so little bits of code like this are good methods for learning a bit more.

Here's the function:

 def uptime():  
   '''  
   Return uptimes based on seconds since last boot  
   '''  
   with open('/proc/uptime', 'r') as f:  
     uptime_seconds = float(f.readline().split()[0])  
     seconds = str(int(uptime_seconds % 60))  
     minutes = str(int(uptime_seconds /60 % 60))  
     hours = str(int(uptime_seconds / 60 / 60 % 24))  
     days = str(int(uptime_seconds / 60 /60 / 24))    
     # Time unit strings  
     time_d = ' days, '  
     time_h = ' hours, '  
     time_m = ' minutes'  
     time_s = ' seconds.'  
     # Change time strings for lower units, prepend zeros  
   if int(days) == 1:  
     time_d = ' day, '      
   if int(hours) <= 9:  
     hours = '0' + hours  
     if int(hours) == 1:  
       time_h = 'hour '    
   if int(minutes) <= 9:  
     minutes = '0' + minutes  
     if int(minutes) == 1:  
       time_m = ' minute '        
   if int(seconds) <= 9:  
     seconds = '0' + seconds  
     if int(seconds) == 1:  
       time_s = ' second.'  
   print("")        
   print(days + time_d + hours + ':' + minutes + ':' + seconds)  
   print('Uptime is ' +days + time_d + hours + time_h + minutes + time_m +' and ' + seconds + time_s)  

It's not much, but it works. I've put an in loop in there to decide if the output should print "seconds" or "second", "minutes" or "minute", "hours" or "hour", "days" or "day."

Here's the output that you get:

 mugwriter@interzone ~ $ python my_uptime2.py   
 0 days, 00:42:12  
 Uptime is 0 days, 00 hours, 42 minutes and 12 seconds.  

There are two lines of output there, comment out the one that you don't like if you want to take the code.  Feel free to add it to your .profile or something if you find it useful