2011-07-20

Tell me when!

Today I was waiting at school for a RAID to be ready to be mounted. I got tired of trying the "mount" command over and over; the computer should tell me when it's ready. I ended up writing this python script to tell me when it was ready:

#!/usr/bin/env python
# tell-me-when

import os
import sys
import time

from optparse import OptionParser

usage = '%prog {[options]} [command]'
parser = OptionParser (usage=usage)
parser.add_option ('-d', '--delay', dest='delay', default=5,
        type=float, metavar='T', help='delay T seconds between tries')
opts, args = parser.parse_args ()
command = args[0]

while True:
    result = os.system (command)
    if result == 0:
        zenity_command = 'zenity --info --title="Success!" ' \
            + '--text=\'Command "' + command + '" has completed successfully.\''
        os.system (zenity_command)
        break
    else:
        print '%s - "%s" still fails...' % (time.ctime (), command)
        time.sleep (opts.delay)

I called it like so:

$ sudo tell-me-when -d 10 'mount /mnt/i3store0/'

The script tries running the given command until it returns an exit status of 0, at which point it displays a message box informing the user that the command has succeeded. In the mean time, it prints a message in the shell with the current time for each failed try.

The program could easily be extended to play a sound upon success, but I haven't implemented that yet since my work computer doesn't have speakers.

2011-07-01

Timing a shell script

Time some shell script code without the "time" command:

before=`date +%s`

# code goes here

after=`date +%s`
elapsed_seconds="$(expr $after - $before)"
echo Elapsed time: $(date -d $elapsed_seconds +%H:%M:%S)