Linux 如何删除使用 tempfile.mkdtemp 创建的目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6884991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete a directory created with tempfile.mkdtemp?
提问by Yesheng Li
I have a python program that creates temporary directories under /temp
by using tempfile.mkdtemp
. Unfortunately, the Python program did not delete the directory after using it. So now the disk space is low.
我有一个 python 程序,它/temp
使用tempfile.mkdtemp
. 遗憾的是,Python 程序使用后并没有删除该目录。所以现在磁盘空间不足。
Questions:
问题:
- How do I delete the temporary directories left under
/temp
manually? I tried to delete them manually but got "permission denied" error. - In the Python program, how to delete
temp
directory after using them?
- 如何
/temp
手动删除留下的临时目录?我试图手动删除它们,但收到“权限被拒绝”错误。 - 在Python程序中,
temp
使用后如何删除目录?
回答by simplylizz
Read the documentation, it's simple. ;) From the docs: the directory is readable, writable, and searchable only by the creating user ID.
阅读文档,很简单。;) 来自文档:该目录只能通过创建用户 ID 读取、写入和搜索。
To delete temp directory try something like this:
要删除临时目录,请尝试以下操作:
import errno
import shutil
import tempfile
try:
tmp_dir = tempfile.mkdtemp() # create dir
# ... do something
finally:
try:
shutil.rmtree(tmp_dir) # delete directory
except OSError as exc:
if exc.errno != errno.ENOENT: # ENOENT - no such file or directory
raise # re-raise exception
Also you can try tempdirpackage or see its sources.
您也可以尝试tempdir包或查看其来源。
回答by Nils von Barth
To manage resources (like files) in Python, best practice is to use the with
keyword, which automatically releases the resources (i.e., cleans up, like closing files); this is available from Python 2.5.
在 Python 中管理资源(如文件),最佳实践是使用with
关键字,它会自动释放资源(即清理,如关闭文件);这可以从 Python 2.5 获得。
From Python 3.2, you can use tempfile.TemporaryDirectory()
instead of tempfile.mkdtmp()
– this is usable in with
and automatically cleans up the directory:
从 Python 3.2 开始,您可以使用tempfile.TemporaryDirectory()
代替tempfile.mkdtmp()
– 这可用于with
并自动清理目录:
from tempfile import TemporaryDirectory
with TemporaryDirectory() as temp_dir:
# ... do something with temp_dir
# automatically cleaned up when context exited
If you are using an earlier version of Python (at least 2.5, so have with
), you can use backports.tempfile; see Nicholas Bishop's answerto tempfile.TemporaryDirectory context manager in Python 2.7.
如果您使用的是早期版本的 Python(至少 2.5,所以有with
),您可以使用backports.tempfile;看到尼古拉斯主教的回答到tempfile.TemporaryDirectory上下文管理器在Python 2.7。
It's easy and instructive to roll your own class, called a
context manager.The return value of the __enter__()
method is bound to the target of the as
clause, while the __exit__()
method is called when the context is exited – even by exception – and performs cleanup.
推出自己的类,称为上下文管理器,既简单又
有益。该__enter__()
方法的返回值绑定到as
子句的目标,而该__exit__()
方法在退出上下文时被调用 - 即使是异常 - 并执行清理。
import shutil
import tempfile
class TemporaryDirectory(object):
"""Context manager for tempfile.mkdtemp() so it's usable with "with" statement."""
def __enter__(self):
self.name = tempfile.mkdtemp()
return self.name
def __exit__(self, exc_type, exc_value, traceback):
shutil.rmtree(self.name)
You can simplify this with the @contextlib.contextmanager
decorator, so you don't need to write a context manager manually. The code prior to the yield
is executed when entering the context, the yielded value is bound to the target of the as
, and the code after the yield
is executed when exiting the context. This is fundamentally a coroutinethat encapsulates the resource acquisition and release, with the yield
yielding control to the suite(body) of the with
clause. Note that here you doneed to have a try...finally
block, as @contextlib.contextmanager
does not catch exceptions in the yield
– this just factors the resource management into a coroutine.
您可以使用@contextlib.contextmanager
装饰器简化此操作,因此您无需手动编写上下文管理器。之前的代码在yield
进入上下文时执行,产生的值绑定到 的目标上as
, 之后的代码在yield
退出上下文时执行。这基本上是一个封装了资源获取和释放的协程,对子句yield
的套件(主体)进行了让步控制with
。请注意,这里您确实需要一个try...finally
块,因为@contextlib.contextmanager
它不会捕获异常yield
——这只是将资源管理纳入协程。
from contextlib import contextmanager
import tempfile
import shutil
@contextmanager
def TemporaryDirectory():
name = tempfile.mkdtemp()
try:
yield name
finally:
shutil.rmtree(name)
As simplylizz notes, if you don't mind the directory already being deleted (which the above code assumes does not happen), you can catch the “No such file or directory” exception as follows:
正如简单的lizz所指出的,如果您不介意目录已经被删除(上面的代码假设不会发生),您可以捕获“没有这样的文件或目录”异常,如下所示:
import errno
# ...
try:
shutil.rmtree(self.name)
except OSError as e:
# Reraise unless ENOENT: No such file or directory
# (ok if directory has already been deleted)
if e.errno != errno.ENOENT:
raise
You can compare with the standard implementation in tempfile.py
; even this simple class has had bugs and evolved over the years.
您可以与 中的标准实现进行比较tempfile.py
;即使是这个简单的类也有错误并且多年来不断发展。
For background on with
, see:
有关 的背景with
,请参阅:
- The Python Tutorial: Methods of File Objects
- With Statement Context Managers
- PEP 343 -- The "with" Statement
- Python 教程:文件对象的方法
- 使用语句上下文管理器
- PEP 343 -- “with” 声明
回答by mohammed wazeem
I think the user is responsible for deleting the temporary directory and its content created by using tempfile.mkdtemp(). it will not deleted automatically just like temporary file. There are many ways you can delete the directory
我认为用户负责删除使用 tempfile.mkdtemp() 创建的临时目录及其内容。它不会像临时文件一样自动删除。有很多方法可以删除目录
If the directory is empty you can use
如果目录为空,您可以使用
`os.removedirs or os.rmdir`
Note it can be used only if the directory is empty otherwise will raise
注意它只能在目录为空时使用,否则会引发
OSError
操作系统错误
This will delete the entire directory path:
这将删除整个目录路径:
import shutil
shutil.rmtree('/path/to/your/dir/')
be careful while using this, it will delete the whole directory and files inside it.
使用时要小心,它会删除整个目录和其中的文件。
回答by Ali Avc?
I have had the same/similar problem using TemporaryDirectory() which is basically covering the functionality you defined above.
我在使用 TemporaryDirectory() 时遇到了相同/类似的问题,它基本上涵盖了您在上面定义的功能。
My problem was due to the usage of the temporary directory. I used to populate the content by cloning a git repository, it happened that there were read-only files created during the process and with a normal exit these read-only temp files were causing the complete temporary directory to stay there.
我的问题是由于使用了临时目录。我曾经通过克隆 git 存储库来填充内容,碰巧在此过程中创建了只读文件,并且在正常退出时,这些只读临时文件导致完整的临时目录留在那里。
Did inherit the TemporaryDirectory to my own class and did override the class method _cleanup with the following code.
确实将 TemporaryDirectory 继承到我自己的类,并使用以下代码覆盖了类方法 _cleanup。
The code before super() might be optimized but for me, the performance was not the problem.
super() 之前的代码可能会被优化,但对我来说,性能不是问题。
I did use the force and read the source of "tempfile"
我确实使用了力量并阅读了“ tempfile”的来源
import tempfile
import shutil
import stat
class myTempDir(tempfile.TemporaryDirectory):
@classmethod
def _cleanup(self,name, warn_message):
for root, dirs, files in os.walk(name):
for fname in files:
full_path = os.path.join(root, fname)
os.chmod(full_path ,stat.S_IWRITE)
super()
Solution worked for Windows 10 with Python 3
解决方案适用于使用 Python 3 的 Windows 10