Pythonã§ä¸¦åå®è¡ããã
æè¿æ²¢å±±ã®ç»åããç¹å®ã®é¨åã®ã¿ãæãåºãã¨ãããããªå¦çããã¦ããã®ã ãç¹ã«åç»åã¨ã®éã«é¢é£ã¯ãªãã®ã§1ããã»ã¹ãã¤åããããæ°ããã»ã¹åæã«åããã¦ä¸¦åå®è¡ããããã¨ã調ã¹ã.
ä»åã¯ä¾ã¨ãã¦é©å½ã«100000æã®ç»åããããããã¯000000.jpg - 100000.jpgã¨ããæãã§ãã¡ã¤ã«ãåå¨ãã¦ããã¨ãã.ã¾ããããã®ç»åãé©å½ãªé¢æ°ã®å¦çã«ããã¦å¥ã®ãã£ã¬ã¯ããªã«ä¿åãã.ä¾ãã°Pythonã§ãããã®100000æã®ç»åã«ä»¥ä¸ã®æ§ãªé¢æ°å¦çãæ½ãã¨ããã.
# source, destã¨ãã«ãã¡ã¤ã«ã®ãã¹ # sourceã¯å ãã¡ã¤ã«ã®ãã¹, destã¯å¦çãããã¡ã¤ã«ãä¿åãããã¹ def example(source, dest): print(source + "ãå¦çãã¦" + save + "ã«ä¿åãã¾ãã")
ãããªã¨ãLinuxãMacã§ããã°æ¬¡ã®ãããªæãã§å®è¡ããã¨ããæãã«ä¸¦è¡å®è¡ãã¦ããã.
$ find $SOURCE_PATH -type f | gawk -F/ '{print $NF}' | xargs -I{} -P $n python3 logo_cutter.py $SOURCE_PATH/{} $SAVE_PATH/{}
xargsã®Pãªãã·ã§ã³ã¯ãªãã¨ããããã¨ã«ãã®ããã»ã¹ã並è¡å®è¡ãã¦ããã.
ãªã®ã§ããã§å°ã£ã¦ããªãã£ãã®ã ãå®å®¶ã®ãã·ã³ã¯Windowsã§Linuxã¯å ¥ã£ã¦ããªã.ã¾ãä½åº¦ãPythonãå¼ã³åºãã®ã¯ã³ã¹ããæãããããªæ°ããã. ããã§Pythonã§ä¸¦åå®è¡ã§ããªãã調ã¹ã¦ã¿ã.
ããã¨ã©ãããæ¨æºã©ã¤ãã©ãªã«multiprocessingãªãå¼·ãããªã©ã¤ãã©ãªãçºè¦ãã. ãã¡ãã¨Windowsã§ããµãã¼ããã¦ãããããã.
調ã¹ã¦æ¬¡ã®ãããªã³ã¼ããæ¸ãã.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import multiprocessing as mp import os import sys import time def hoge(source, dest): time.sleep(0.01) print("PID:" + str(os.getpid()) + ": " + source + "ã" + dest + "ã«ä¿åãã¾ãã") def wrapper_hoge(tuple_data): return tuple_data[0](tuple_data[1], tuple_data[2]) if __name__ == "__main__": if len(sys.argv) != 3: print("python3 example.py <SOURCE_PATH> <DEST_PATH>") sys.exit(1) source_path = sys.argv[1] dest_path = sys.argv[2] # å ¥åå¤ããã¹ã§ãããã®ç¢ºèª assert os.path.isdir(dest_path) and os.path.isdir(save_path), True source = [os.path.abspath(source_path + x) for x in os.listdir(source_path)] dests = [os.path.abspath(dest_path + x) for x in os.listdir(dest_path)] p = mp.Pool(4) # ããã»ã¹æ° data = [(hoge, x, y) for x, y in zip(dests, saves)] p.map(wrapper_hoge, data)
ç°¡åã«è§£èª¬ããã¨
source = [os.path.abspath(source_path + x) for x in os.listdir(source_path)]
ã®é¨åã¯
find $SOURCE_PATH -type f
ã¨åãå¦çããã¦ãã. ãã¨Pythonã¯å¤æ°ã«é¢æ°ãªãã¸ã§ã¯ããæ ¼ç´ãããã¨ãã§ããã®ã§
data = [(hoge, x, y) for x, y in zip(dests, saves)]
ããããã¨ãã§ãã.
ä»åã®å ´åãããããã¯ã¨ããèµ·ãããã¨ããªãã®ã§é常ã«ç°¡åãªå®è£ ã§å®ç¾ãããã¨ãã§ãã.ããã§Windowsã§ãxargsçã使ããã¨ãå©ç¨ã§ãã. ãã¨æè¿åå¼·ãã ããGoã§ã¯é¢æ°ã«ä¸¦åå®è¡ããçãªå½ä»¤ãã¤ããã ãã§ãã£ã¦ããããããã®ã§æãããã°ããã調ã¹ãã.