我在使用 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 标志,但我确信在主进程中打开的文件句柄是closed在多处理儿童中。
明显的解决方法是将文件名作为参数传递给子进程的 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)