当前位置: 首页>>代码示例>>Python>>正文


Python NamedTemporaryFile.__exit__方法代码示例

本文整理汇总了Python中tempfile.NamedTemporaryFile.__exit__方法的典型用法代码示例。如果您正苦于以下问题:Python NamedTemporaryFile.__exit__方法的具体用法?Python NamedTemporaryFile.__exit__怎么用?Python NamedTemporaryFile.__exit__使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tempfile.NamedTemporaryFile的用法示例。


在下文中一共展示了NamedTemporaryFile.__exit__方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ZipGenerator

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __exit__ [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
开发者ID:NERC-CEH,项目名称:ftw.zipexport,代码行数:57,代码来源:generation.py

示例2: _NamedTemporaryFileWithContent

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __exit__ [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)
开发者ID:cgorbit,项目名称:rem,代码行数:14,代码来源:subprocsrv_fallback.py

示例3: AtomicFileWriter

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __exit__ [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)
开发者ID:simpkins,项目名称:avrpp,代码行数:28,代码来源:usb_config.py

示例4: working_file

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __exit__ [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()
开发者ID:RoyHsiao,项目名称:zipline,代码行数:48,代码来源:cache.py

示例5: sky_share

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __exit__ [as 别名]
def sky_share(subproc, directory, files):
    out = NamedTemporaryFile('w')

    argv = ['sky', 'share', '-d', directory] + files
    logging.debug(argv)

    # FIXME collect STDERR
    try:
        p = subproc.Popen(argv, stdout=out.name)
    except:
        try:
            raise
        finally:
            try:
                out.__exit__(None, None, None)
            except:
                pass

    def finalize(exit_code):
        try:
            status = exit_code.get()
            if status:
                raise RuntimeError("sky share failed with exit status: %d" % status)

            with open(out.name) as in_:
                id = in_.readline().rstrip('\n')

            if not id.startswith('rbtorrent:'):
                raise RuntimeError('Malformed output of sky share: %s' % id[:100])

            return id

        finally:
            try:
                out.__exit__(None, None, None)
            except:
                pass

    return wrap_future(p.get_returncode_future(), finalize)
开发者ID:cgorbit,项目名称:rem,代码行数:41,代码来源:resource_sharing.py

示例6: working_file

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __exit__ [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)
开发者ID:zzhao6,项目名称:zipline,代码行数:39,代码来源:cache.py

示例7: ZipGenerator

# 需要导入模块: from tempfile import NamedTemporaryFile [as 别名]
# 或者: from tempfile.NamedTemporaryFile import __exit__ [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
开发者ID:4teamwork,项目名称:ftw.zipexport,代码行数:86,代码来源:generation.py


注:本文中的tempfile.NamedTemporaryFile.__exit__方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。