我遇到了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 . . .
在创建新进程期间,文件句柄似乎以某种方式“丢失”。有人可以解释一下发生了什么吗?
答案 0 :(得分:7)
过去我遇到过类似的问题。不确定它是在多处理模块中完成还是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)