Python 2.7中的tempfile.TemporaryDirectory上下文管理器
有没有办法用Python 2.7在上下文管理器中创建临时目录Python 2.7中的tempfile.TemporaryDirectory上下文管理器,python,python-2.7,with-statement,temp,Python,Python 2.7,With Statement,Temp,有没有办法用Python 2.7在上下文管理器中创建临时目录 with tempfile.TemporaryDirectory() as temp_dir: # modify files in this dir # here the temporary diretory does not exist any more. 已添加到Python 3.2中的tempfile标准库中 它是tempfile.mkdtemp的简单包装器。它是用纯Python编写的,可以很容易地移植到Python
with tempfile.TemporaryDirectory() as temp_dir:
# modify files in this dir
# here the temporary diretory does not exist any more.
已添加到Python 3.2中的tempfile标准库中
它是tempfile.mkdtemp
的简单包装器。它是用纯Python编写的,可以很容易地移植到Python2.7
例如:
from __future__ import print_function
import warnings as _warnings
import os as _os
from tempfile import mkdtemp
class TemporaryDirectory(object):
"""Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:
with TemporaryDirectory() as tmpdir:
...
Upon exiting the context, the directory and everything contained
in it are removed.
"""
def __init__(self, suffix="", prefix="tmp", dir=None):
self._closed = False
self.name = None # Handle mkdtemp raising an exception
self.name = mkdtemp(suffix, prefix, dir)
def __repr__(self):
return "<{} {!r}>".format(self.__class__.__name__, self.name)
def __enter__(self):
return self.name
def cleanup(self, _warn=False):
if self.name and not self._closed:
try:
self._rmtree(self.name)
except (TypeError, AttributeError) as ex:
# Issue #10188: Emit a warning on stderr
# if the directory could not be cleaned
# up due to missing globals
if "None" not in str(ex):
raise
print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
file=_sys.stderr)
return
self._closed = True
if _warn:
self._warn("Implicitly cleaning up {!r}".format(self),
ResourceWarning)
def __exit__(self, exc, value, tb):
self.cleanup()
def __del__(self):
# Issue a ResourceWarning if implicit cleanup needed
self.cleanup(_warn=True)
# XXX (ncoghlan): The following code attempts to make
# this class tolerant of the module nulling out process
# that happens during CPython interpreter shutdown
# Alas, it doesn't actually manage it. See issue #10188
_listdir = staticmethod(_os.listdir)
_path_join = staticmethod(_os.path.join)
_isdir = staticmethod(_os.path.isdir)
_islink = staticmethod(_os.path.islink)
_remove = staticmethod(_os.remove)
_rmdir = staticmethod(_os.rmdir)
_warn = _warnings.warn
def _rmtree(self, path):
# Essentially a stripped down version of shutil.rmtree. We can't
# use globals because they may be None'ed out at shutdown.
for name in self._listdir(path):
fullname = self._path_join(path, name)
try:
isdir = self._isdir(fullname) and not self._islink(fullname)
except OSError:
isdir = False
if isdir:
self._rmtree(fullname)
else:
try:
self._remove(fullname)
except OSError:
pass
try:
self._rmdir(path)
except OSError:
pass
import os
with TemporaryDirectory() as tmp_dir:
print("Temporary directory path: %s" % tmp_dir)
print(os.path.isdir(tmp_dir))
# here the temporary diretory does not exist any more.
print(os.path.isdir(tmp_dir))
from\uuuuu future\uuuuu导入打印功能
将警告导入为\u警告
将操作系统导入为\u操作系统
从tempfile导入mkdtemp
类临时目录(对象):
“”“创建并返回一个临时目录。此目录具有相同的
行为类似于mkdtemp,但可以用作上下文管理器
例子:
使用TemporaryDirectory()作为tmpdir:
...
退出上下文后,目录和包含的所有内容
在它里面,所有的东西都被移除了。
"""
def uuu init uuuu(self,后缀=”,前缀=“tmp”,dir=None):
self.\u closed=False
self.name=None#处理引发异常的mkdtemp
self.name=mkdtemp(后缀、前缀、目录)
定义报告(自我):
返回“”。格式(self.\u类\u.\u名称\u,self.name)
定义输入(自我):
返回self.name
def清除(自,警告=False):
如果self.name而不是self.\u关闭:
尝试:
self.\u rmtree(self.name)
除(TypeError,AttributeError)外,例如:
#问题#10188:在stderr上发出警告
#如果无法清理目录
#由于丢失了全球卫星
如果str中没有“无”(例如):
提升
打印(“清除{!r}时出错:{!r}”)。格式(例如,self,),
文件=_sys.stderr)
返回
self.\u closed=True
如果警告:
self.\u warn(“隐式清理{!r}”)。格式(self),
资源(警告)
定义退出(自身、exc、值、tb):
self.cleanup()
定义(自我):
#如果需要隐式清理,则发出ResourceWarning
self.cleanup(_warn=True)
#XXX(ncoghlan):下面的代码试图
#该类允许模块调零过程
#这发生在CPython解释器关闭期间
#唉,它实际上并没有管理好它。见第10188期
_listdir=staticmethod(_os.listdir)
_path\u join=staticmethod(\u os.path.join)
_isdir=staticmethod(_os.path.isdir)
_islink=staticmethod(_os.path.islink)
_remove=staticmethod(_os.remove)
_rmdir=静态方法(_os.rmdir)
_warn=\u warnings.warn
定义树(自身,路径):
#本质上是shutil.rmtree的精简版本。我们不能
#使用globals,因为它们在关机时可能不存在。
对于self.\u listdir(路径)中的名称:
fullname=self.\u路径\u连接(路径,名称)
尝试:
isdir=self.\u isdir(全名)而非self.\u islink(全名)
除操作错误外:
isdir=False
如果是isdir:
self.\u rmtree(全名)
其他:
尝试:
自我删除(全名)
除操作错误外:
通过
尝试:
self.\u rmdir(路径)
除操作错误外:
通过
导入操作系统
使用临时目录()作为tmp_目录:
打印(“临时目录路径:%s”%tmp\u dir)
打印(os.path.isdir(tmp_dir))
#这里不再存在临时指令。
打印(os.path.isdir(tmp_dir))
另一个选项是pypi上的“backports.tempfile”包:
引用该项目的描述:“这个包在backports名称空间下的Python的tempfile模块中提供了新特性的backports。”
安装时使用:
pip install backports.tempfile
然后在脚本中使用它:
from backports import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
# modify files in this dir
# here the temporary directory does not exist any more.
如果
=staticmethod(thing)
行不起作用,也许应该将它们删除?是否缺少打印(…file=\u sys.stderr)
的导入sys as\u sys
?源链接:复杂的代码也是由于在完成过程中试图清理,如果关闭时上下文管理器未正确关闭。这导致了并被简化了。比起复制+粘贴代码片段,我更喜欢这一点。非常感谢。我希望我的问题现在不会获得接近票数,因为我更喜欢图书馆。有关图书馆的问题应转到。。。顺便说一句:我是在开玩笑,我不明白为什么会有sofwarerecs网站。为什么不询问有关StackOverFlow的软件建议的问题…令人烦恼的是,backport没有将所有现有的tempfile
都别名化,因此您可能需要两者。有关如何手动执行此操作的信息,请参阅。