【发布时间】:2014-08-19 06:08:28
【问题描述】:
以下代码有效:
import multiprocessing
import threading
import time
file_path = 'C:/TEST/0000.txt'
class H(object):
def __init__(self, path):
self.hash_file = open(file_path, 'rb')
def read_line(self):
print self.hash_file.readline()
h = H(file_path)
h.read_line()
但是当我在进程中使用时:
import multiprocessing
import threading
import time
file_path = 'C:/TEST/0000.txt'
class Worker(multiprocessing.Process):
def __init__(self, path):
super(Worker, self).__init__()
self.hash_file = open(path, 'rb')
def run(self):
while True:
for i in range(1000):
print self.hash_file.readline()
time.sleep(1.5)
if __name__ == '__main__':
w = Worker(file_path)
w.start()
w.join()
引发异常:
Process Worker-1:
Traceback (most recent call last):
File "E:\Python27\lib\multiprocessing\process.py", line 258, in _bootstrap
self.run()
File "C:\ts_file_open.py", line 31, in run
print self.hash_file.readline()
ValueError: I/O operation on closed file
因为open的成本很高,我只需要读取文件,我认为打开一次就足够了。但是为什么进程运行时这个文件对象会关闭?而且我还想把这个文件对象传递给子进程和子进程的子线程。
【问题讨论】:
-
尝试在
run()方法中打开文件。 -
@monkut 我知道这行得通,但为什么呢?
-
您在一个进程中创建 Worker 实例,并在另一个进程中调用 run。
-
@monkut 这个行为有点奇怪。
-
@monkut 我看到
Popen正在处理start方法。这似乎是重点。
标签: python file python-2.7 multiprocessing