本文整理汇总了Python中tempfile.NamedTemporaryFile.__enter__方法的典型用法代码示例。如果您正苦于以下问题:Python NamedTemporaryFile.__enter__方法的具体用法?Python NamedTemporaryFile.__enter__怎么用?Python NamedTemporaryFile.__enter__使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile.NamedTemporaryFile
的用法示例。
在下文中一共展示了NamedTemporaryFile.__enter__方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AtomicFileWriter
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __enter__ [as 别名]
class AtomicFileWriter(object):
def __init__(self, path, tmp_prefix=None, encoding='utf-8'):
self.name = path
output_dir, base = os.path.split(path)
if tmp_prefix is None:
tmp_prefix = base + '.'
self.tmpf = NamedTemporaryFile(dir=output_dir, prefix=tmp_prefix,
mode='w', encoding=encoding,
delete=False)
def __enter__(self):
self.tmpf.__enter__()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
tmp_name = self.tmpf.name
result = self.tmpf.__exit__(exc_type, exc_value, exc_traceback)
if result or exc_type is None:
os.rename(tmp_name, self.name)
else:
os.unlink(tmp_name)
return result
def write(self, data):
return self.tmpf.write(data)
示例2: ZipGenerator
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __enter__ [as 别名]
class ZipGenerator(object):
"""
Generates the zip. Acts as context manager to ensure that all temporary
files are deleted after usage.
"""
def __init__(self):
self.empty = True
def __enter__(self):
self.tmp_file = NamedTemporaryFile(prefix="plone_zipexport_")
self.tmp_file.__enter__()
self.zip_file = ZipFile(self.tmp_file.name, "w", allowZip64=True)
self.zip_file.__enter__()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.zip_file.__exit__(exc_type, exc_value, traceback)
self.tmp_file.__exit__(exc_type, exc_value, traceback)
def add_file(self, file_path, file_pointer):
# paths in zipfile do not have a / at the root
file_path = file_path.strip('/')
file_path = self.generate_unique_filepath(file_path)
try:
self.zip_file.writefile(file_pointer, file_path)
except RuntimeError:
raise StandardError("ZipFile already generated/closed. "
"Please add all files before generating.")
self.empty = False
def generate_unique_filepath(self, file_path):
if file_path not in self.zip_file.namelist():
return file_path
path, name = os.path.split(file_path)
name, ext = os.path.splitext(name)
for i in xrange(2, sys.maxint):
new_filename = os.path.join(path, '%s (%d)%s' % (name, i, ext))
if new_filename not in self.zip_file.namelist():
return new_filename
@property
def is_empty(self):
return self.empty
def generate(self):
if self.tmp_file is None:
raise StandardError(
"Please use ZipGenerator as a context manager.")
self.zip_file.close()
return self.tmp_file
示例3: working_file
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __enter__ [as 别名]
class working_file(object):
"""A context manager for managing a temporary file that will be moved
to a non-temporary location if no exceptions are raised in the context.
Parameters
----------
final_path : str
The location to move the file when committing.
*args, **kwargs
Forwarded to NamedTemporaryFile.
Notes
-----
The file is moved on __exit__ if there are no exceptions.
``working_file`` uses :func:`shutil.move` to move the actual files,
meaning it has as strong of guarantees as :func:`shutil.move`.
"""
def __init__(self, final_path, *args, **kwargs):
self._tmpfile = NamedTemporaryFile(delete=False, *args, **kwargs)
self._final_path = final_path
@property
def path(self):
"""Alias for ``name`` to be consistent with
:class:`~zipline.utils.cache.working_dir`.
"""
return self._tmpfile.name
def _commit(self):
"""Sync the temporary file to the final path.
"""
self._tmpfile.close()
move(self._name, self._final_path)
def __getattr__(self, attr):
return getattr(self._tmpfile, attr)
def __enter__(self):
self._tmpfile.__enter__()
return self
def __exit__(self, *exc_info):
self._tmpfile.__exit__(*exc_info)
if exc_info[0] is None:
self._commit()
示例4: _NamedTemporaryFileWithContent
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __enter__ [as 别名]
class _NamedTemporaryFileWithContent(object):
def __init__(self, content):
self._file = NamedTemporaryFile()
self._file.write(content)
self._file.flush()
self._file.file.seek(0)
def __enter__(self):
return self._file.__enter__()
def __exit__(self, *args):
self._file.__exit__(*args)
示例5: working_file
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __enter__ [as 别名]
class working_file(object):
"""A context manager for managing a temporary file that will be moved
to a non-temporary location if no exceptions are raised in the context.
Parameters
----------
final_path : str
The location to move the file when committing.
*args, **kwargs
Forwarded to NamedTemporaryFile.
Notes
-----
The file is moved on __exit__ if there are no exceptions.
``working_file`` uses :func:`shutil.copyfile` to move the actual files,
meaning it has as strong of guarantees as :func:`shutil.copyfile`.
"""
def __init__(self, final_path, *args, **kwargs):
self._tmpfile = NamedTemporaryFile(*args, **kwargs)
self._final_path = final_path
def _commit(self):
"""Sync the temporary file to the final path.
"""
copyfile(self.name, self._final_path)
def __getattr__(self, attr):
return getattr(self._tmpfile, attr)
def __enter__(self):
self._tmpfile.__enter__()
return self
def __exit__(self, *exc_info):
if exc_info[0] is None:
self._commit()
self._tmpfile.__exit__(*exc_info)
示例6: ZipGenerator
# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __enter__ [as 别名]
class ZipGenerator(object):
"""
Generates the zip. Acts as context manager to ensure that all temporary
files are deleted after usage.
"""
def __init__(self, path_normalizer=normalize_path):
self.empty = True
self.path_normalizer = path_normalizer
def __enter__(self):
self.tmp_file = NamedTemporaryFile(prefix="plone_zipexport_")
self.tmp_file.__enter__()
self.zip_file = ZipFile(self.tmp_file.name, "w", allowZip64=True)
self.zip_file.__enter__()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.zip_file.__exit__(exc_type, exc_value, traceback)
self.tmp_file.__exit__(exc_type, exc_value, traceback)
def add_folder(self, folder_path):
folder_path = safe_unicode(folder_path)
# Always add a slash at the end of the path
folder_path = u'{}/'.format(folder_path.strip('/'))
# Creates a new empty folder
self.zip_file.writestr(zipfile.ZipInfo(folder_path), '')
self.empty = False
def add_file(self, file_path, file_pointer):
if self.path_normalizer is not None:
file_path = self.path_normalizer(file_path)
else:
file_path = safe_unicode(file_path)
# paths in zipfile do not have a / at the root
file_path = file_path.strip('/')
file_path = self.generate_unique_filepath(file_path)
if not self.check_disk_has_space_for_file(file_pointer):
raise NotEnoughSpaceOnDiskException()
try:
self.zip_file.writefile(file_pointer, file_path)
except RuntimeError:
raise StandardError("ZipFile already generated/closed. "
"Please add all files before generating.")
self.empty = False
def generate_unique_filepath(self, file_path):
if file_path not in self.zip_file.namelist():
return file_path
path, name = os.path.split(file_path)
name, ext = os.path.splitext(name)
for i in xrange(2, sys.maxint):
new_filename = os.path.join(path, '%s (%d)%s' % (name, i, ext))
if new_filename not in self.zip_file.namelist():
return new_filename
def check_disk_has_space_for_file(self, file_d):
disk_stat = os.statvfs(self.tmp_file.name)
bytes_free = disk_stat.f_frsize * disk_stat.f_bavail
position = file_d.tell()
file_d.seek(0, os.SEEK_END)
file_size = file_d.tell() - position
file_d.seek(position)
return file_size < bytes_free
@property
def is_empty(self):
return self.empty
def generate(self):
if self.tmp_file is None:
raise StandardError(
"Please use ZipGenerator as a context manager.")
self.zip_file.close()
return self.tmp_file