2014-06-12 17 views
0

我想在某些數據不適合內存的情況下使用memmap,並且使用memmap將代碼欺騙的想法僅僅是一個ndarray。爲了進一步擴展這種使用memmap的方式,我想知道是否有可能重載memmap的取消引用操作符來刪除memmap文件。在Python中,當memmap對象不再被引用時,是否有可能重載Numpy的memmap來刪除它自己?

因此,例如:

from tempfile import mkdtemp 
import os.path as path 
filename = path.join(mkdtemp(), 'tmpfile.dat') 
{ 
    out = np.memmap(filename, dtype=a.dtype, mode='w+', shape=a.shape) 
} 
# At this point out is out of scope, so the overloaded 
# dereference function would delete tmpfile.dat 

這聽起來是可行的/有這個已經完成?有沒有我沒有想到的東西?

謝謝!

+2

「引用操作」? –

+4

'{''}'?! 'from __future__ import braces' ... – glglgl

+0

你確定不想使用'with'上下文管理器嗎? 'with'是Python如何進行基於範圍的資源管理;這與C++的RAII最爲接近。 – user2357112

回答

1

只是在文件被打開後刪除該文件np.memmap 該文件將在關閉文件描述符的最後一個引用後被系統刪除。

蟒蛇臨時文件這樣的工作,可以很方便地與with背景下馬槽構建序列:

with tempfile.NamedTemporaryFile() as f: 
    # file gone now from the filesystem 
    # but f still holds a reference so it still exists and uses space (see /prof<pid>/fd) 
    # open it again (will not work on windows) 
    x = np.memmap(f.name, dtype=np.float64, mode='w+', shape=(3,4)) 
# file path is unlinked but exists on disk with the open file reference in x 
del x 
# now all references are gone and the file is properly deleted 
+0

這是錯誤的。甚至在調用'del x'之前,'os.path.exists(x.filename)'是'False'。 'x'只能引用'f.name',一個字符串,而不是'f'對象本身。 – Gilly

+0

該路徑不再存在,但該文件不會被刪除,直到其最後一個引用被刪除。 'x'持有對文件的引用,這就是np.memmap的工作原理,它打開'f.name'指向的內容,所以需要刪除它。它與上下文管理器刪除的python對象「f」無關,這是OS文件系統的一個屬性。 – jtaylor

+0

啊,這很有道理。你能否改變文字來清楚這一點?也許'#f引用現在消失了,但x仍然有一個引用' - >'#文件路徑未鏈接,但在磁盤上存在打開的文件引用「? – Gilly

相關問題