當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。