[ Python ] Jupyter에서 multiprocessing을 활용하여 bash 돌리기

2019. 5. 1. 17:42분석 Python/구현 및 자료

728x90

** 유용하셨다면 공감버튼 한번씩 눌러주세요**

import os , re , time 
import numpy as np 
from multiprocessing import Pool     
path = "/home/advice/Python/SR/" 
DIR = os.listdir(path)



## 원하는 Scripy ~.py를 찾기
dir2 = [ path + i for i in DIR if re.search("BayesOpt", i)]



curr_path = os.getcwd()  +"/" + str(date.today()) 
## 폴더 추가
if not os.path.exists(curr_path): 
    os.makedirs(curr_path)



## .sh 파일 여러개 생성하기

for idx , i in enumerate(dir2) : 
    with open (curr_path + "/" + str(idx) + '.sh', 'w') as rsh: 
        text = '''#!/bin/sh \npython {} \n'''.format(i) 
        rsh.write(text)



## 멀티프로세싱을 활용하기 위해 사용한 bash 모아두기

## 굳이 .py로 해도 되지만, argparse 구조 같은 거 미리 만들어서 sh에 돌리면 더 깔끔하게 돌릴 수 있다.

shell_say = [ curr_path + "/" + i for i in os.listdir(curr_path) if re.search(".sh", i )]





## 멀티프로세싱으로 bash 한꺼번에 돌리기 

def main(i) : 
    os.system("sh {}".format(shell_say[i]))

if __name__ == '__main__': 
    pool = Pool(len(shell_say)) 
    # pool = Pool()  would use the number of available processors instead 
    pool.map(main, np.arange(len(shell_say)).tolist()) 
    pool.close() 
    pool.join()

 

 

참고 

 

How to run parallel processes?

This week I ran into a case were I should run several scripts with analysis that could run simultaneously. The analysis results would then…

medium.com

 

 

 

728x90