2011-12-21 3 views
1

안녕하세요. 저는 파이썬으로 프로그래밍을 시작했으며 subprocess.Popen을 사용하여 "make"를 사용하여 컴파일하는 프로그램의 여러 인스턴스를 실행하려고합니다. 그러나 "make"를하기 전에 텍스트 처리를 수행하고 "make"가 사용할 파일 세트를 생성해야합니다. 이제 생성 된 여러 파일을 동시에 사용하여 동일한 프로그램을 실행하고 프로그램 출력의 모든 인스턴스 출력을 동일한 파일에 쓰고 싶습니다. 인스턴스의 수에 따라 많은 텍스트 파일을 생성해야합니다. 본질적으로, 나는 첫 번째 for 루프 아래의 모든 작업을 동시에 수행하고 싶습니다. 동시에 'n'번 말할 수 있습니다. 어떤 도움을 주시면 크게 감사하겠습니다 :). 시스템에 여러 개의 프로세서 또는 코어가있는 경우서브 프로세스의 다중 인스턴스 .Popen

for mC in range(monteCarlo): 
    print "Simulation Number",str(mC+1),"of",str(monteCarlo) 
    L = numpy.zeros((1,4),float) 
    W = numpy.zeros((1,4),float) 
    i = 0 
    j = 0 
    with open("1t.sp", "r") as inFile: 
     with open("2t.sp","w") as outFile: 
      line = inFile.readline() 
      while (line != ""): 
       newLine = [] 
       for words in line.split(): 
        if words.startswith("W="): 
         W[0,i] = float(words[2:].replace('n',''))*random.normalvariate(1,widthDeviation) 
         #print i,words,str('W='+str(W[i]).strip('[]')+'n').replace(" ","") 
         words = str('W='+str(W[0,i]).strip('[]')+'n').replace(" ","") 
         i = i+1 
        elif words.startswith("L="): 
         L[0,j] = float(words[2:].replace('n',''))*random.normalvariate(1,lengthDeviation) 
         #print j,words,str('L='+str(L[j]).strip('[]')+'n').replace(" ","") 
         words = str('L='+str(L[0,j]).strip('[]')+'n').replace(" ","") 
         j = j+1 
        newLine.append(words) 
      #print newLine 
       outFile.write(" ".join(newLine)) 
       outFile.write("\n") 
       line = inFile.readline() 
    outFile.close() 
    inFile.close() 
    openWrite.write(str(W).strip('[]')) 
    openWrite.write(str(L).strip('[]')) 
    call(["make"]) 
    fRate = (open("tf.log","r").readlines()[34]).split()[-2] 
    cSect = (open("tf.log","r").readlines()[35]).split()[-2] 
    openWrite.write("\t") 
    openWrite.write(fRate) 
    openWrite.write(" ") 
    openWrite.write(cSect) 
    openWrite.write("\n") 
openWrite.close() 

답변

1

당신은 동시에 파이썬 기능을 실행하기 위해 multiprocessing module를 사용하여 해당 활용할 수 있습니다 :

import multiprocessing as mp 

def run_mc(mC): 
    print "Simulation Number", str(mC+1), "of", str(monteCarlo) 
    ... 
    call(["make"]) 
    fRate = (open("tf.log", "r").readlines()[34]).split()[-2] 
    cSect = (open("tf.log", "r").readlines()[35]).split()[-2] 
    return fRate, cSect 

def log_result(result): 
    # This is called whenever run_mc returns a result. 
    # result is modified only by the main process, not the pool workers. 
    fRate, cSect = result 
    with open(..., 'a') as openWrite: 
     openWrite.write('\t{f} {c}\n'.format(f = fRate, c = cSect)) 

def main(): 
    # mp.Pool creates a pool of worker processes. By default it creates as many 
    # workers as the system has processors. When the problem is CPU-bound, there 
    # is no point in making more. 
    pool = mp.Pool() 
    for mC in range(monteCarlo): 
     # This will call run_mc(mC) in a worker process. 
     pool.apply_async(run_mc, args = (mC), callback = log_result) 

if __name__ == '__main__': 
    main() 
+0

이 필요한 많은 텍스트 파일 "만드는 것이 생성 것인가 ". 그 의미에서, 어떻게하면 어떤 텍스트 파일을 입력으로 사용할 지 알 수 있습니다. 또는 나는 무엇인가 놓치고있다?? – shrikanth

+0

죄송합니다. 나는 그것에 관심을 기울이지 않았습니다. 'run_mc'에서'dirname = str (mC + 1)'을 사용하여 새 디렉토리 ('os.makedirs (dirname)')를 만들고 디렉토리를 변경하고 ('os.chdir (dirname)') 작업 할 수 있습니다 그곳에. – unutbu

+1

그건 그렇고,'with'-block 구문을 사용하기 때문에'outFile.close()'와'inFile.close()'를 명시 적으로 호출 할 필요가 없습니다. 파이썬이 블록을 종료하면 파일 핸들이 닫힙니다. – unutbu