Python多处理,ValueError:关闭文件的I / O操作

我遇到了
Python多处理程序包的问题.下面是一个简单的示例代码,说明了我的问题.

import multiprocessing as mp
import time

def test_file(f):
  f.write("Testing...\n")
  print f.name
  return None

if __name__ == "__main__":
  f = open("test.txt", 'w')
  proc = mp.Process(target=test_file, args=[f])
  proc.start()
  proc.join()

当我运行它时,我收到以下错误.

Process Process-1:
Traceback (most recent call last):
  File "C:\Python27\lib\multiprocessing\process.py", line 258, in _bootstrap
    self.run()
  File "C:\Python27\lib\multiprocessing\process.py", line 114, in run
    self.target(*self._args, **self._kwargs)
  File "C:\Users\Ray\Google Drive\Programming\Python\tests\follow_test.py", line 24, in test_file
    f.write("Testing...\n")
ValueError: I/O operation on closed file
Press any key to continue . . .

似乎在创建新进程期间文件句柄以某种方式“丢失”.有人可以解释一下发生了什么吗?

最佳答案 我过去也遇到过类似的问题.不确定它是否在多处理模块中完成,或者open是否默认设置了close-on-exec标志,但我确信在主进程中打开的文件句柄在多处理子节点中是关闭的.

显而易见的解决方法是将文件名作为参数传递给子进程的init函数,并在每个子进程中打开一次(如果使用池),或者将其作为参数传递给目标函数并在每个子进程上打开/关闭调用.前者需要使用全局来存储文件句柄(不是一件好事) – 除非有人可以告诉我如何避免这种情况:) – 后者可能会导致性能损失(但可以直接用于multiprocessing.Process ).

前者的例子:

filehandle = None

def child_init(filename):
    global filehandle
    filehandle = open(filename,...)
    ../..

def child_target(args):
    ../..

if __name__ == '__main__':
    # some code which defines filename
    proc = multiprocessing.Pool(processes=1,initializer=child_init,initargs=[filename])
    proc.apply(child_target,args)
点赞