Last active
July 20, 2016 00:34
-
-
Save yabberyabber/6e93b56bf4bf45c8bd5e52f68ab15852 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 FileLock: | |
def __init__( self, lockfile, delay=1.0 ): | |
self.is_locked = False | |
self.lockfile = lockfile | |
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( 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. | |
These arguments aren't implemented yet cuz I can't figure out how to implement them... | |
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