【发布时间】:2015-03-10 13:58:42
【问题描述】:
我正在并行运行多个子进程,但我需要锁定每个进程,直到子进程给出输出(通过打印功能)。子进程正在运行已打包为可执行文件的 python 脚本。
代码如下:
import multiprocessing as mp
import subprocess
import os
def main(args):
l,inpath = args
l.acquire()
print "Running KNN.exe for files in %s" % os.path.normpath(inpath).split('\\')[-1]
#Run KNN executable as a subprocess
subprocess.call(os.path.join(os.getcwd(), "KNN.exe"))
#This is where I want to wait for any output from the subprocess before releasing the lock
l.release()
#Here I would like to wait until subprocess is done then print that it is done
l.acquire()
print "Done %s" % os.path.normpath(inpath).split('\\')[-1]
l.release()
if __name__ == "__main__":
#Set working directory path containing input text file
os.chdir("C:\Users\Patrick\Google Drive\KNN")
#Get folder names in directory containing GCM input
manager = mp.Manager()
l = manager.Lock()
gcm_dir = "F:\FIDS_GCM_Data_CMIP5\UTRB\UTRB KNN-CAD\Input"
paths = [(l, os.path.join(gcm_dir, folder)) for folder in os.listdir(gcm_dir)]
#Set up multiprocessing pool
p = mp.Pool(mp.cpu_count())
#Map function through input paths
p.map(main, paths)
所以目标是锁定进程,以便子进程可以运行,直到收到输出。之后可以释放锁并且子进程可以继续,直到它完成,然后我想打印它已经完成。
我的问题是如何在释放进程上的锁(多个)之前等待子进程的单个(并且唯一)输出?
另外,我怎样才能等待进程终止然后打印它已完成?
【问题讨论】:
标签: python locking multiprocessing subprocess