ninestarsの日記: マルチコア時代のコマンド実行 1
こちらのお話し。
bash はそういうの想定してないよね~ということでpythonで最低限のものを作ってみました。標準入力から与えられたコマンドを実行し、返り値とコマンドをstderrへ出力。引数として同時実行数を与える。
実行はこんな感じで。
$ cat cmdlist | python mpexec.py 4
注:実行されるコマンドからのstdout, stderrは関与しない。
python2.x(2.4,2.5は別途processingモジュールのインストールが必要)。
実行を中止するときはC-c ではなく kill。
#!/usr/bin/env python
# coding: utf-8
import sys
from subprocess import call
try:
from processing import Pool
except ImportError:
from multiprocessing import Pool
def shell(cmd):
retcode = call(cmd, shell=True)
return retcode, cmd
def main():
pool = Pool(int(sys.argv[1]))
cmd_list = [line.rstrip() for line in sys.stdin]
it = pool.imap(shell, cmd_list)
for retcode, cmd in it:
sys.stderr.write('%d\t%s\n' % (retcode, cmd))
if __name__ == '__main__':
main()
ちょっと変更 (スコア:1)
元のコードではコマンドの投入順に結果が表示されたが、終了順の方がいいかなと考え、変更してみた。
やっつけ感も増していいのではないかと。
#!/usr/bin/env python
# coding: utf-8
import sys
from subprocess import call
try:
from processing import Pool
except ImportError:
from multiprocessing import Pool
def shell(cmd):
retcode = call(cmd, shell=True)
sys.stderr.write('%d\t%s\n' % (retcode, cmd))
def main():
pool = Pool(int(sys.argv[1]))
cmd_list = [line.rstrip() for line in sys.stdin]
pool.imap(shell, cmd_list)
pool.close()
pool.join()
if __name__ == '__main__':
main()