Created
July 20, 2016 00:23
-
-
Save yabberyabber/ad39fd7e4ebf99ee0a8148ad65ab1de9 to your computer and use it in GitHub Desktop.
for when you wanna run a bunch of commands in serial but each in a different terminal and you don't care what order they run in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys, os, subprocess, errno, time | |
class BadArgsException( Exception ): | |
pass | |
class FileLock: | |
def __init__( self, lockfile, delay=1.0 ): | |
""" Acquire the lock, if possible. If the lock is in use, it check again | |
every `wait` seconds. It does this until it either gets the lock or | |
exceeds `timeout` number of seconds, in which case it throws | |
an exception. | |
""" | |
self.is_locked = False | |
self.lockfile = lockfile | |
self.delay = delay | |
while True: | |
try: | |
self.fd = os.open( self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR ) | |
break; | |
except OSError as e: | |
if e.errno != errno.EEXIST: | |
raise | |
time.sleep( self.delay ) | |
self.is_locked = True | |
def release( self ): | |
if self.is_locked: | |
os.close( self.fd ) | |
os.unlink( self.lockfile ) | |
self.is_locked = False | |
def __del__( self ): | |
self.release() | |
def printUsage(): | |
print """Usage: mutex <lockfile> [OPTIONS] <command [command-arg1 [command-arg2, [ ... ]]> | |
Wait until <lockfile> does not exist, then run the given command. | |
The lockfile must be the first argument... the command to run must be the last. | |
The -s argument means to unlock the file when the command is blocked waiting for stdin. | |
The -k argument means to kill the file when the command is blocked waiting for stdin. | |
""" | |
def parseArgs( argv ): | |
lockfile = argv[0] | |
options = {} | |
commandMode = False | |
command = [] | |
for arg in argv[ 1: ]: | |
if commandMode: | |
command.append( arg ) | |
elif arg[0] == '-': | |
for option in arg[ 1: ]: | |
options[ option ] = True | |
else: | |
command.append( arg ) | |
commandMode = True | |
return lockfile, options, command | |
def runCmd( lockfile, options, cmd ): | |
lock = FileLock( lockfile ) | |
subprocess.call( ' '.join( cmd ), shell=True ) | |
lock.release() | |
def main(): | |
try: | |
lockfile, options, cmd = parseArgs( sys.argv[ 1: ] ) | |
except Exception: | |
printUsage() | |
return 1 | |
runCmd( lockfile, options, cmd ) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment