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


Python zipfile.py方法代码示例

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


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

示例1: test_write_python_directory

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def test_write_python_directory(self):
        os.mkdir(TESTFN2)
        try:
            with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
                fp.write("print(42)\n")

            with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
                fp.write("print(42 * 42)\n")

            with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
                fp.write("bla bla bla\n")

            zipfp  = zipfile.PyZipFile(TemporaryFile(), "w")
            zipfp.writepy(TESTFN2)

            names = zipfp.namelist()
            self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
            self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
            self.assertNotIn('mod2.txt', names)

        finally:
            rmtree(TESTFN2) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:24,代码来源:test_zipfile.py

示例2: test_write_python_directory

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def test_write_python_directory(self):
        os.mkdir(TESTFN2)
        try:
            with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
                fp.write("print(42)\n")

            with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
                fp.write("print(42 * 42)\n")

            with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
                fp.write("bla bla bla\n")

            zipfp  = zipfile.PyZipFile(TemporaryFile(), "w")
            zipfp.writepy(TESTFN2)

            names = zipfp.namelist()
            self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
            self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
            self.assertNotIn('mod2.txt', names)

        finally:
            shutil.rmtree(TESTFN2) 
开发者ID:dxwu,项目名称:BinderFilter,代码行数:24,代码来源:test_zipfile.py

示例3: test_write_python_directory

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def test_write_python_directory(self):
        os.mkdir(TESTFN2)
        try:
            with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
                fp.write("print(42)\n")

            with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
                fp.write("print(42 * 42)\n")

            with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
                fp.write("bla bla bla\n")

            with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
                zipfp.writepy(TESTFN2)

                names = zipfp.namelist()
                self.assertCompiledIn('mod1.py', names)
                self.assertCompiledIn('mod2.py', names)
                self.assertNotIn('mod2.txt', names)

        finally:
            rmtree(TESTFN2) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:24,代码来源:test_zipfile.py

示例4: test_write_python_directory_filtered

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def test_write_python_directory_filtered(self):
        os.mkdir(TESTFN2)
        try:
            with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
                fp.write("print(42)\n")

            with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
                fp.write("print(42 * 42)\n")

            with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
                zipfp.writepy(TESTFN2, filterfunc=lambda fn:
                                                  not fn.endswith('mod2.py'))

                names = zipfp.namelist()
                self.assertCompiledIn('mod1.py', names)
                self.assertNotIn('mod2.py', names)

        finally:
            rmtree(TESTFN2) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:21,代码来源:test_zipfile.py

示例5: test_write_pyfile_bad_syntax

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def test_write_pyfile_bad_syntax(self):
        os.mkdir(TESTFN2)
        try:
            with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
                fp.write("Bad syntax in python file\n")

            with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
                # syntax errors are printed to stdout
                with captured_stdout() as s:
                    zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))

                self.assertIn("SyntaxError", s.getvalue())

                # as it will not have compiled the python file, it will
                # include the .py file not .pyc
                names = zipfp.namelist()
                self.assertIn('mod1.py', names)
                self.assertNotIn('mod1.pyc', names)

        finally:
            rmtree(TESTFN2) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:23,代码来源:test_zipfile.py

示例6: test_write_pyfile_bad_syntax

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def test_write_pyfile_bad_syntax(self):
        os.mkdir(TESTFN2)
        try:
            with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
                fp.write("Bad syntax in python file\n")

            with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
                # syntax errors are printed to stdout
                with captured_stdout() as s:
                    zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))

                self.assertIn("SyntaxError", s.getvalue())

                # as it will not have compiled the python file, it will
                # include the .py file not .pyc or .pyo
                names = zipfp.namelist()
                self.assertIn('mod1.py', names)
                self.assertNotIn('mod1.pyc', names)
                self.assertNotIn('mod1.pyo', names)

        finally:
            rmtree(TESTFN2) 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:24,代码来源:test_zipfile.py

示例7: resolve_symlink

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def resolve_symlink(path):
  """Processes path containing symlink on Windows.

  This is needed to make ../swarming_bot/main_test.py pass on Windows because
  git on Windows renders symlinks as normal files.
  """
  if not is_windows():
    # Only does this dance on Windows.
    return path
  parts = os.path.normpath(path).split(os.path.sep)
  for i in range(2, len(parts)):
    partial = os.path.sep.join(parts[:i])
    if os.path.isfile(partial):
      with open(partial) as f:
        link = f.read()
      assert '\n' not in link and link, link
      parts[i-1] = link
  return os.path.normpath(os.path.sep.join(parts)) 
开发者ID:luci,项目名称:luci-py,代码行数:20,代码来源:bot_archive.py

示例8: _create_zipinfo

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def _create_zipinfo(self, filename, arcname, compress_type):
        # type: (Text, Optional[Text], Optional[int]) -> zipfile.ZipInfo
        # The main thing that prevents deterministic zip file generation
        # is that the mtime of the file is included in the zip metadata.
        # We don't actually care what the mtime is when we run on lambda,
        # so we always set it to the default value (which comes from
        # zipfile.py).  This ensures that as long as the file contents don't
        # change (or the permissions) then we'll always generate the exact
        # same zip file bytes.
        # We also can't use ZipInfo.from_file(), it's only in python3.
        st = self._osutils.stat(str(filename))
        if arcname is None:
            arcname = filename
        arcname = self._osutils.normalized_filename(str(arcname))
        arcname = arcname.lstrip(os.sep)
        zinfo = zipfile.ZipInfo(arcname, self._default_time_time)
        # The external_attr needs the upper 16 bits to be the file mode
        # so we have to shift it up to the right place.
        zinfo.external_attr = (st.st_mode & 0xFFFF) << 16
        zinfo.file_size = st.st_size
        zinfo.compress_type = compress_type or self.compression
        return zinfo 
开发者ID:aws,项目名称:chalice,代码行数:24,代码来源:utils.py

示例9: open

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info
        if (name in self._expected_hashes
            and self._expected_hashes[name] != None):
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 
开发者ID:jpush,项目名称:jbox,代码行数:36,代码来源:install.py

示例10: choose_archive

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def choose_archive(sub_dict, sub_num=5, query=True):
    """
    传入候选字幕字典,返回选择的字幕包名称,字幕包下载地址

    params:
        sub_dict: dict, check downloader.py
        sub_num: int, maximum number of subtitles
        query: bool, return first sub if False
    return:
        exit: bool
        chosen_subs: str, subtitle name
    """

    exit = False

    if not query:
        chosen_sub = list(sub_dict.keys())[0]
        return exit, chosen_sub

    items = []
    items.append("Exit. Not downloading any subtitles.")
    for i, key in enumerate(sub_dict.keys()):
        if i == sub_num:
            break
        lang_info = ""
        lang_info += "【简】" if 4 & sub_dict[key]["lan"] else "      "
        lang_info += "【繁】" if 2 & sub_dict[key]["lan"] else "      "
        lang_info += "【英】" if 1 & sub_dict[key]["lan"] else "      "
        lang_info += "【双】" if 8 & sub_dict[key]["lan"] else "      "
        sub_info = "%s  %s" % (lang_info, key)
        items.append(sub_info)

    choice = _print_and_choose(items)
    if choice == 0:
        exit = True
        return exit, []

    return exit, list(sub_dict.keys())[choice - 1] 
开发者ID:gyh1621,项目名称:GetSubtitles,代码行数:40,代码来源:util.py

示例11: guess_subtitle

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def guess_subtitle(sublist, video_detail):
    """
    传入字幕列表,视频信息,返回得分最高字幕名

    params:
        sublist: list of str
        video_detail: result of guessit
    return:
        success: bool
        subname: str
    """

    if not sublist:
        return False, None

    scores, subs = [], []
    for one_sub in sublist:
        _, ftype = path.splitext(one_sub)
        if ftype not in SUB_FORMATS:
            continue
        subs.append(one_sub)
        subname = path.split(one_sub)[-1]  # extract subtitle name
        try:
            # zipfile:/Lib/zipfile.py:1211 Historical ZIP filename encoding
            # try cp437 encoding
            subname = subname.encode("cp437").decode("gbk")
        except Exception:
            pass
        score = compute_subtitle_score(video_detail, subname)
        scores.append(score)

    max_score = max(scores)
    max_pos = scores.index(max_score)
    return max_score > 0, subs[max_pos] 
开发者ID:gyh1621,项目名称:GetSubtitles,代码行数:36,代码来源:util.py

示例12: zip_info_from_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def zip_info_from_file(cls, filename, arcname=None, date_time=None):
    """Construct a ZipInfo for a file on the filesystem.

    Usually this is provided directly as a method of ZipInfo, but it is not implemented in Python
    2.7 so we re-implement it here. The main divergance we make from the original is adding a
    parameter for the datetime (a time.struct_time), which allows us to use a deterministic
    timestamp. See https://github.com/python/cpython/blob/master/Lib/zipfile.py#L495."""
    st = os.stat(filename)
    isdir = stat.S_ISDIR(st.st_mode)
    if arcname is None:
      arcname = filename
    arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
    while arcname[0] in (os.sep, os.altsep):
      arcname = arcname[1:]
    if isdir:
      arcname += '/'
    if date_time is None:
      date_time = time.localtime(st.st_mtime)
    zinfo = zipfile.ZipInfo(filename=arcname, date_time=date_time[:6])
    zinfo.external_attr = (st.st_mode & 0xFFFF) << 16  # Unix attributes
    if isdir:
      zinfo.file_size = 0
      zinfo.external_attr |= 0x10  # MS-DOS directory flag
    else:
      zinfo.file_size = st.st_size
    return zinfo 
开发者ID:pantsbuild,项目名称:pex,代码行数:28,代码来源:common.py

示例13: __init__

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def __init__(self, zip_info):
        self.last_modified = float(datetime(*zip_info.date_time).timestamp())
        # https://github.com/python/cpython/blob/3.8/Lib/zipfile.py#L392
        self.mode = zip_info.external_attr >> 16
        self.size = zip_info.file_size

        for k in ('filename', 'orig_filename', 'comment', 'create_system',
                  'create_version', 'extract_version', 'flag_bits',
                  'volume', 'internal_attr', 'external_attr', 'CRC',
                  'header_offset', 'compress_size', 'compress_type'):
            setattr(self, k, getattr(zip_info, k)) 
开发者ID:pfnet,项目名称:pfio,代码行数:13,代码来源:zip.py

示例14: test_write_python_package

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def test_write_python_package(self):
        import email
        packagedir = os.path.dirname(email.__file__)
        self.requiresWriteAccess(packagedir)

        with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
            zipfp.writepy(packagedir)

            # Check for a couple of modules at different levels of the
            # hierarchy
            names = zipfp.namelist()
            self.assertCompiledIn('email/__init__.py', names)
            self.assertCompiledIn('email/mime/text.py', names) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:15,代码来源:test_zipfile.py

示例15: open

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import py [as 别名]
def open(self, name_or_info, mode="r", pwd=None):
        """Return file-like object for 'name'."""
        # A non-monkey-patched version would contain most of zipfile.py
        ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd)
        if isinstance(name_or_info, zipfile.ZipInfo):
            name = name_or_info.filename
        else:
            name = name_or_info

        if name in self._expected_hashes and self._expected_hashes[name] is not None:
            expected_hash = self._expected_hashes[name]
            try:
                _update_crc_orig = ef._update_crc
            except AttributeError:
                warnings.warn('Need ZipExtFile._update_crc to implement '
                              'file hash verification (in Python >= 2.7)')
                return ef
            running_hash = self._hash_algorithm()
            if hasattr(ef, '_eof'):  # py33
                def _update_crc(data):
                    _update_crc_orig(data)
                    running_hash.update(data)
                    if ef._eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            else:
                def _update_crc(data, eof=None):
                    _update_crc_orig(data, eof=eof)
                    running_hash.update(data)
                    if eof and running_hash.digest() != expected_hash:
                        raise BadWheelFile("Bad hash for file %r" % ef.name)
            ef._update_crc = _update_crc
        elif self.strict and name not in self._expected_hashes:
            raise BadWheelFile("No expected hash for file %r" % ef.name)
        return ef 
开发者ID:cbrgm,项目名称:telegram-robot-rss,代码行数:36,代码来源:install.py


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