Skip to content

Instantly share code, notes, and snippets.

@vbkaisetsu
Created December 1, 2014 14:13
Show Gist options
  • Save vbkaisetsu/c135cd53cf7aabe336c5 to your computer and use it in GitHub Desktop.
Save vbkaisetsu/c135cd53cf7aabe336c5 to your computer and use it in GitHub Desktop.
複数のマシンでコマンドを並列実行するためのPythonスクリプト
#!/usr/bin/python3
import argparse
import os, sys
import threading
def cmdRunner(cmd):
os.system(cmd)
def main():
"""
recipeファイル内の未実行のコマンドを実行し,実行したコマンドをコメントアウトする。
recipe: 実行したいコマンドを列挙したファイル。
jobs: 実行したい未実行コマンドの個数 または "reset"。
resetを指定した場合は,recipeファイルのコメントアウトされた行をコメントアウトアウトする。
"""
parser = argparse.ArgumentParser()
parser.add_argument("recipe", help="Recipe file")
parser.add_argument("jobs", help="Number of jobs | \"reset\"")
args = parser.parse_args()
if args.jobs != "reset":
recipefile = open(args.recipe, "r")
lines = []
cmds = []
jobs = int(args.jobs)
for line in recipefile:
line = line.rstrip("\n")
if line.strip().startswith("#"):
lines.append(line)
continue
if line.strip() != "" and len(cmds) < jobs:
cmds.append(line)
lines.append("# DONE ** " + line)
else:
lines.append(line)
recipefile.close()
recipefile = open(args.recipe, "w")
for line in lines:
print(line, file=recipefile)
recipefile.close()
tlst = []
for cmd in cmds:
print("Run: " + cmd, file=sys.stderr)
thread = threading.Thread(target=cmdRunner, args=(cmd,))
tlst.append(thread)
thread.daemon = True
thread.start()
for thread in tlst:
thread.join()
else:
recipefile = open(args.recipe, "r")
lines = []
for line in recipefile:
line = line.rstrip("\n")
if line.startswith("# DONE ** "):
line = line[10:]
lines.append(line)
recipefile.close()
recipefile = open(args.recipe, "w")
for line in lines:
print(line, file=recipefile)
recipefile.close()
return
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment