#!/bin/env python import sys import time import subprocess backspace="\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" def SecToWdhms(seconds): m,s = divmod(int(seconds), 60) h,m = divmod(m, 60) #d,h = divmod(h, 24) #w,d = divmod(d, 7) hms=str(str(h)+":"+str(m)+":"+str(s)) return hms def Usage(): print "" print "Description:" print "Count down to 0 and execute a command." print "Usage:" print sys.argv[0]+" <seconds> <command and parameters no quotes>" print "seconds may be expressed as <hr>:<mn>:<sc>" print "" def ErrorOut(errorText=""): if len(errorText) > 0: print str(errorText) Usage() sys.exit() # verify we got some arguments if len(sys.argv) < 3: ErrorOut() seconds=sys.argv[1] command=sys.argv[2] # Check integrity of the first parameter (time) if str(seconds).find(":") > 0: # Convert x:x:x to a large number of seconds seconds=str(seconds).split(":") if len(seconds) < 3: ErrorOut() seconds=int(int(seconds[0])*3600+int(seconds[1])*60+int(seconds[2])) elif not seconds.isdigit(): ErrorOut() # count down startTime=int(time.time()) currentTime=startTime endTime=int(int(startTime)+int(seconds)) while currentTime <= endTime: oldCurrentTime=currentTime print backspace, sys.stdout.flush() secondsLeft=SecToWdhms(str(endTime - currentTime)) print "Time left -> "+str(secondsLeft)+" ", sys.stdout.flush() while oldCurrentTime == currentTime: time.sleep(0.1) currentTime=int(time.time()) print backspace, print "Running command -> "+command # Put the rest of the command line after the command. arguments=[command] if len(sys.argv) > 3: arguments+=sys.argv[3:] # Execute the command subprocess.call(arguments) # dummy print to get the command line to come back after the above command runs. print "" |
This is the same stupid script I wrote to count down and then run a command. Someone (Adam) asked why I don't use cron. Because cron sucks! Down with cron.
The only thing better about this script is the counter. Instead of a sleep, I actually count seconds. The old script lost about four or six seconds an hour. This one adds about a quarter of a second per run regardless of amount of time it is set for.
Regardless of any use this script gets, it is fun practice.
No comments:
Post a Comment