#!/usr/bin/python # Run a command with a lock held. # Copyright 2009 Adam Sampson import sys, os, getopt, fcntl, time, curses def usage(rc): print """Usage: with-lock [OPTIONS] LOCKFILE COMMAND ... Run COMMAND with the file LOCKFILE locked. -q don't print a message while waiting --help display this help and exit Report bugs to .""" sys.exit(rc) def main(args): try: opts, args = getopt.getopt(args, "q", ["help"]) except getopt.GetoptError: usage(1) if len(args) < 2: usage(1) quiet = False for o, a in opts: if o == "-q": quiet = True elif o == "--help": usage(0) if not os.isatty(sys.stdout.fileno()): quiet = True if not quiet: curses.setupterm() ti_el = curses.tigetstr("el") ti_cr = curses.tigetstr("cr") if ti_el is None or ti_cr is None: quiet = True progress = "/-\\|" fd = os.open(args[0], os.O_WRONLY | os.O_CREAT, 0600) while True: try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) break except IOError: pass if not quiet: sys.stdout.write("%s(waiting for lock %s... %s)" % (ti_cr, args[0], progress[0])) progress = progress[1:] + progress[0] sys.stdout.flush() time.sleep(0.2) if not quiet: sys.stdout.write("%s%s" % (ti_cr, ti_el)) sys.stdout.flush() os.execvp(args[1], args[1:]) if __name__ == "__main__": main(sys.argv[1:])