为什么 Python 的临时文件方法 unlink() 需要文件名?



Python的tempfile.unlink()需要一个参数,即要取消链接的实体的名称。由于对象/类知道这一点,并且该方法未记录在临时文件中,恕我直言,似乎只需要它自己的文件名即可取消链接。

允许一个对象上的取消链接方法删除任何任意文件似乎也很奇怪。

还是我错过了其他用例?

Quantum@Mechanic:/tmp$ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> x = tempfile.NamedTemporaryFile(delete=False)
>>> x.name
'/tmp/tmp_It8iM'
>>> x.close()
>>> x.unlink()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly 1 argument (0 given)
>>> x.unlink(x.name)
>>>

深入研究源代码:

import os as _os
unlink = _os.unlink

你发现的是一个实施的意外。 没有记录NamedTemporaryFile.unlink方法,但正如您所看到的,似乎确实存在。 具体来说,它与 os.unlink ,您永远不应该自己调用它,因为它是一个未记录的(错误)功能。

如果你想看到实现,它实际上有一个关于为什么unlink()方法存在的注释(但不完全是为什么它必须有那个令人困惑的名称),请参阅这里:https://github.com/python-git/python/blob/master/Lib/tempfile.py#L387

# NT provides delete-on-close as a primitive, so we don't need
# the wrapper to do anything special.  We still use it so that
# file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
if _os.name != 'nt':
    # Cache the unlinker so we don't get spurious errors at
    # shutdown when the module-level "os" is None'd out.  Note
    # that this must be referenced as self.unlink, because the
    # name TemporaryFileWrapper may also get None'd out before
    # __del__ is called.
    unlink = _os.unlink

如果要删除使用 tempfile.NamedTemporaryFile(delete=False) 创建的内容,请按以下方式执行此操作:

x.close()
os.unlink(x.name)

这避免了依赖于将来可能会更改的实现细节。

最新更新