多处理错误'关闭文件的I / O操作'

时间:2016-10-19 11:04:40

标签: python file-io parallel-processing multiprocessing

我遇到了Python多处理程序包的问题。

我使用此方法运行代码并使用多处理模块:

    import multiprocessing
    from multiprocessing.dummy import Pool as ThreadPool

    def change_file(simulation):
        for line in fileinput.FileInput(directory + '/file.txt', inplace=1):        
            for item in range(1,num_variables+1):
                line = line.replace('some text','other text')
            print (line.rstrip('\n'))

   pool = ThreadPool(2) 
   results = pool.map(change_file, Lists_of_works)
   pool.close() 
   pool.join()

此代码是参数程序的一个组件,程序会创建文件夹来识别模拟。然后在每个文件夹中替换.txt文件的一些文本(根据每种情况不同)。 '目录'名称和替换文本取决于模拟。为了执行模拟,我使用多线程。这是代码中唯一需要使用1个内核的组件,因为当我使用4时,我会收到以下错误:

ValueError: I/O operation on closed file.

我认为原因是因为主进程打开文件而子进程关闭...所以新的主进程使用相同的文件。这个原因在this post

中进行了解释

解决: 解决方案是将文本文件存储在全局变量(字符串)中,然后在帖子解释时替换文本。

谢谢!

0 个答案:

没有答案