2017-02-01 2 views
3

나는 회귀를 실행하기 위해 회귀 변수로 인수를 사용하는 pyataample3.do 파일을 가지고 있습니다. 회귀 분석의 F- 통계는 텍스트 파일에 저장됩니다. 병렬 실행 Stata는 다중 프로세스와 서브 프로세스를 사용하여 파이썬에서 파일을 실행합니다.

clear all 
set more off   
local y `1'   
display `"first parameter: `y'"' 

sysuse auto 
regress price `y' 
local f=e(F) 
display "`f'" 
file open myhandle using test_result.txt, write append 
file write myhandle "`f'" _n 
file close myhandle 
exit, STATA clear 

가 지금은 파이썬에서 병렬로 파일을 하나 개의 텍스트 파일의 모든 F-통계를 작성 않는 STATA를 실행하려고 다음과 같이 코드입니다. 내 CPU에는 4 개의 코어가 있습니다.

import multiprocessing 
    import subprocess 

    def work(staname): 
     dofile = "pyexample3.do" 
     cmd = ["StataMP-64.exe","/e", "do", dofile,staname] 
     return subprocess.call(cmd, shell=False) 

    if __name__ == '__main__': 

     my_list =[ "mpg","rep78","headroom","trunk","weight","length","turn","displacement","gear_ratio" ] 

     my_list.sort() 

     print my_list 

     # Get the number of processors available 
     num_processes = multiprocessing.cpu_count() 

     threads = [] 

     len_stas = len(my_list) 

     print "+++ Number of stations to process: %s" % (len_stas) 

     # run until all the threads are done, and there is no data left 

     for list_item in my_list: 

      # if we aren't using all the processors AND there is still data left to 
      # compute, then spawn another thread 

      if(len(threads) < num_processes): 

       p = multiprocessing.Process(target=work,args=[list_item]) 

       p.start() 

       print p, p.is_alive() 

       threads.append(p) 

      else: 
       for thread in threads: 

       if not thread.is_alive(): 

        threads.remove(thread) 

do 파일은 my_list에 9 개의 문자열이 있으므로 9 번 실행되지만 4 번만 실행됩니다. 그래서 어디서 잘못 되었습니까? 처음 4 개 프로세스가 시작 얻을 후 for list_item in my_list 루프에서

답변

1

는 그 다음 else로 전환 :

for thread in threads: 
    if not thread.is_alive(): 
     threads.remove(thread) 

thread.is_alive()는 차단하지 않습니다 때문에 당신이 볼 수 있듯이,이 루프는 그 어떤없이 즉시 실행하세요 4 개의 프로세스가 작업을 완료합니다. 따라서 처음 4 개의 프로세스 만 총 실행됩니다.

당신은 단순히 지속적으로 작은 간격으로 프로세스 상태를 확인하기 위해 while 루프를 사용할 수 있습니다

keep_checking = True 

while keep_checking: 
    for thread in threads: 
     if not thread.is_alive(): 
      threads.remove(thread) 
      keep_checking = False 

    time.sleep(0.5) # wait 0.5s 
+0

를 이제 파일을하는 것은 7 번 실행하지만, 여전히 2 시간이 누락되었습니다. 0.5s가 변경되면 숫자도 변경됩니다. 그것은 텍스트 파일에 동시 쓰기로 인해 발생합니까? – user20726

+0

수 있습니다. 동일한 파일에 쓰는 것이 스레드로부터 안전하지 않기 때문에 다른 프로세스의 파일에 동시에 쓰는 경우 예기치 않은 결과가 발생할 수 있으므로 'RLock'을 사용하여 프로세스가 하나만 있는지 확인하는 것이 좋습니다 동시에 파일 작업. – Shane