Python多处理,ValueError:关闭文件上的I/O操作
我对Python多处理程序包有问题。下面是一个简单的示例代码,说明了我的问题Python多处理,ValueError:关闭文件上的I/O操作,python,file,multiprocessing,Python,File,Multiprocessing,我对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, ar
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)
如果单击左上角的console图标,您将找到选择和复制文本的菜单选项。请使用该功能将回溯作为文本复制到您的帖子中。。。您可能希望将输出转储到队列中,当所有进程都完成时,将输出从队列中弹出,并通过主进程将其写出。谢谢!我希望其他对象不会出现类似的问题。你知道吗?