【问题标题】:file close automaticlly when using it in process文件在进程中使用时自动关闭
【发布时间】: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


【解决方案1】:

这会失败,因为您正在父进程中打开文件,但尝试在子进程中使用它。来自父进程的文件描述符不会被 Windows 上的子进程继承(因为它没有使用os.fork 创建新进程),因此子进程中的读取操作失败。请注意,这段代码实际上可以在 Linux 上运行,因为由于os.fork 的性质,文件描述符会被子进程继承。

另外,我不认为open 操作本身特别昂贵。实际上读取文件可能很昂贵,但打开操作本身应该很快。

【讨论】:

  • Per PEP 446 所有描述符现在在 Windows 和 unix 下的 Python 3.4+ 中默认是不可继承的。这个 PEP 添加了一堆new functions。在 __init__ 方法中添加 os.set_inheritable(self.hash_file.fileno(),False) 应该可以使其在 3.4+ 的 Windows 中工作(但在 unix 中不是必需的,因为它是多处理调用而不是子进程调用)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
  • 1970-01-01
相关资源
最近更新 更多