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


Python tarfile.is_tarfile函数代码示例

本文整理汇总了Python中tarfile.is_tarfile函数的典型用法代码示例。如果您正苦于以下问题:Python is_tarfile函数的具体用法?Python is_tarfile怎么用?Python is_tarfile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: parser_check

def parser_check():
	dirs,files = xbmcvfs.listdir(base_dir)
	if not dirs:
		dirpackages,filespackages = xbmcvfs.listdir(parser_packages_folder)
		if filespackages:
			for fich in filespackages:
				shutil.copyfile(os.path.join(parser_packages_folder,fich), os.path.join(parser_core_folder,fich))
				xbmc.sleep(100)
				import tarfile
				if tarfile.is_tarfile(os.path.join(parser_core_folder,fich)):
					download_tools().extract(os.path.join(parser_core_folder,fich),parser_core_folder)
					download_tools().remove(os.path.join(parser_core_folder,fich))
		else:
			dirsuserdata,files = xbmcvfs.listdir(parser_folder)
			for fich in files:
				dictionary_module = eval(readfile(os.path.join(parser_folder,fich)))
				if "url" in dictionary_module.keys():
					add_new_parser(dictionary_module["url"])
				else:
					xbmcvfs.copy(os.path.join(parser_packages_folder,fich.replace('.txt','.tar.gz')),os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz')))
					import tarfile
					if tarfile.is_tarfile(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))):
						download_tools().extract(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz')),parser_core_folder)
						download_tools().remove(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz')))
	else: pass
	return
开发者ID:Antimoni,项目名称:P2P-Streams-XBMC,代码行数:26,代码来源:parsers.py

示例2: check_volumes_result

def check_volumes_result(target_folder):
    with (target_folder / "Manifest.yml").open("rt") as f:
        manifest = next(yaml.load_all(f))
    volumes = manifest["volumes"]
    assert len(volumes["project"]) == 1
    volume = volumes["project"]["care"]
    assert volume == "care.tar"
    archive = target_folder / "volumes" / "project" / volume
    assert archive.is_file()
    assert tarfile.is_tarfile(str(archive))
    assert count_dir_contents(target_folder / "volumes" / "project") == 1
    assert len(volumes["services"]) == 1
    assert len(volumes["services"]["foo"]) == 2
    volume = volumes["services"]["foo"]["/volume"]
    archive = target_folder / "volumes" / "services" / volume
    assert archive.is_file()
    assert tarfile.is_tarfile(str(archive))
    volume = volumes["services"]["foo"]["/image_volume1"]
    archive = target_folder / "volumes" / "services" / volume
    assert archive.is_file()
    assert tarfile.is_tarfile(str(archive))
    assert count_dir_contents(target_folder / "volumes" / "services") == 2
    assert len(volumes["mounted"]) == 3
    assert (target_folder / "volumes" / "mounted" / "asset.txt").is_file()
    assert (target_folder / "volumes" / "mounted" / "assets").is_dir()
    assert (target_folder / "volumes" / "mounted" / "assets" / "dummy").is_file()
    assert (target_folder / "volumes" / "mounted" / "local").is_dir()
    assert (target_folder / "volumes" / "mounted" / "local" / "dummy").is_file()
    assert count_dir_contents(target_folder / "volumes" / "mounted") == 3
开发者ID:funkyfuture,项目名称:compose-dump,代码行数:29,代码来源:test_backup_volumes.py

示例3: runTest

 def runTest(self):
     """Unpack tarfile relative to srcdir"""
     try:
             tarfile.is_tarfile(self.filepath)
             logger.debug("Tarfile Acquired: %s"%self.filepath)
     except IOError, err:
             self.fail("%s is not a tarfile."%self.filepath)
开发者ID:DeviceTestFramework,项目名称:dtest,代码行数:7,代码来源:unpack_source.py

示例4: zip_file

def zip_file(zip_main_file_path, zip_main_file_name, main_directory, definitions, _totals_):
    tmp_dir = main_directory + '/temp_unzips'
    zip_list = Ziplevels()
    zip_list.path = zip_main_file_path
    zip_list.name = zip_main_file_name
    zip_list.tmp_dir = os.path.join(tmp_dir, os.path.splitext(zip_list.name)[0])
    classes = [zip_list]
    try:
        for mylists in classes:
            if not os.path.exists(mylists.tmp_dir):
                os.makedirs(mylists.tmp_dir)
            z_file = tarfile.open(mylists.path) if tarfile.is_tarfile(mylists.path) else ZipFile(mylists.path)
            with z_file as zip_dir_path:
                zip_dir_path.extractall(path=mylists.tmp_dir)
                for (tmp_dir_name, tmp_sub_dir, tmp_file_name) in os.walk(mylists.tmp_dir, topdown=True):
                    for zip_file_name in tmp_file_name:
                        tmp_dir_path = os.path.join(tmp_dir_name, zip_file_name)
                        if zipfile.is_zipfile(zip_file_name) or tarfile.is_tarfile(tmp_dir_path):
                            temp_list = Ziplevels()
                            temp_list.path = tmp_dir_path
                            temp_list.name = zip_file_name
                            temp_list.tmp_dir = os.path.splitext(tmp_dir_path)[0]
                            classes.append(temp_list)
                        else:
                            file_check(tmp_dir_path, zip_file_name, main_directory, definitions, _totals_,
                                       zip_main_file_name)
        shutil.rmtree(tmp_dir)
    except Exception as e:
        log(zip_main_file_path + '  Is not a valid zipfile', str(e))
开发者ID:YourFriendCaspian,项目名称:dotfiles,代码行数:29,代码来源:nocoin.py

示例5: test_make_tarball

    def test_make_tarball(self):
        # creating something to tar
        root_dir, base_dir = self._create_files('')

        tmpdir2 = self.mkdtemp()
        # force shutil to create the directory
        os.rmdir(tmpdir2)
        # working with relative paths
        work_dir = os.path.dirname(tmpdir2)
        rel_base_name = os.path.join(os.path.basename(tmpdir2), 'archive')

        with support.change_cwd(work_dir):
            base_name = os.path.abspath(rel_base_name)
            tarball = make_archive(rel_base_name, 'gztar', root_dir, '.')

        # check if the compressed tarball was created
        self.assertEqual(tarball, base_name + '.tar.gz')
        self.assertTrue(os.path.isfile(tarball))
        self.assertTrue(tarfile.is_tarfile(tarball))
        with tarfile.open(tarball, 'r:gz') as tf:
            self.assertEqual(sorted(tf.getnames()),
                             ['.', './file1', './file2',
                              './sub', './sub/file3', './sub2'])

        # trying an uncompressed one
        with support.change_cwd(work_dir):
            tarball = make_archive(rel_base_name, 'tar', root_dir, '.')
        self.assertEqual(tarball, base_name + '.tar')
        self.assertTrue(os.path.isfile(tarball))
        self.assertTrue(tarfile.is_tarfile(tarball))
        with tarfile.open(tarball, 'r') as tf:
            self.assertEqual(sorted(tf.getnames()),
                             ['.', './file1', './file2',
                              './sub', './sub/file3', './sub2'])
开发者ID:erichiller,项目名称:cmder,代码行数:34,代码来源:test_shutil.py

示例6: diff_ggl

    def diff_ggl(self):
        args = self.args
        filename1, filename2, layout1, layout2 = args.f, args.F, args.l, args.L

        csvlayout1 = open(layout1, "r") if layout1 else None
        csvlayout2 = open(layout2, "r") if layout2 else None

        if tarfile.is_tarfile(filename1):
            paramconfig1, csvlayout1 = self.extract_from_ggl(filename1)
        else:
            paramconfig1 = open(filename1, "r")

        if tarfile.is_tarfile(filename2):
            paramconfig2, csvlayout2 = self.extract_from_ggl(filename2)
        else:
            paramconfig2 = open(filename2, "r")

        if paramconfig1 is not None and paramconfig2 is not None and csvlayout1 is not None and csvlayout2 is not None:
            params1 = self.read_paramconfig(paramconfig1, csvlayout1)
            params2 = self.read_paramconfig(paramconfig2, csvlayout2)
            self.compare(params1, params2)
            if type(paramconfig1) is file:
                paramconfig1.close()
            if type(paramconfig2) is file:
                paramconfig2.close()
            if type(csvlayout1) is file:
                csvlayout1.close()
            if type(csvlayout2) is file:
                csvlayout2.close()
        else:
            print args_parser.parse_args(["diff", "ggl", "-h"])

        return
开发者ID:alpha-jacobshih,项目名称:pyjects,代码行数:33,代码来源:pptb.py

示例7: is_tarfile

def is_tarfile(arg):
	"""Helper function to test if a given filepath/file-like-object is of a
	tar like file.

	Limitation: We use name extension to determine this if the arg is a
	file-like-object. Valid extions are 'tar', 'gz', 'bz', 'bz2'."""
	if isinstance(arg, str):
		# Process filepaths
		tarfile.is_tarfile(arg)
	elif hasattr(arg, 'name'):
		# At the moment, we cannot check bytestreams for being tar files
		return os.path.splitext(arg.name)[-1] in ['tar', 'gz', 'bz', 'bz2']
	return False
开发者ID:abn,项目名称:pyrus,代码行数:13,代码来源:archives.py

示例8: unpackArchive

def unpackArchive(archiveFile, targetBaseDir, subdir):
	"""Unpack archive into a directory"""

	if subdir and not subdir.endswith('/'):
		subdir += '/'
	# unpack source archive
	if tarfile.is_tarfile(archiveFile):
		tarFile = tarfile.open(archiveFile, 'r')
		members = None
		if subdir:
			members = [
				member for member in tarFile.getmembers()
				if member.name.startswith(subdir)
			]
			if not members:
				sysExit('sub-directory %s not found in archive' % subdir)
		tarFile.extractall(targetBaseDir, members)
		tarFile.close()
	elif zipfile.is_zipfile(archiveFile):
		zipFile = zipfile.ZipFile(archiveFile, 'r')
		names = None
		if subdir:
			names = [
				name for name in zipFile.namelist()
				if name.startswith(subdir)
			]
			if not names:
				sysExit('sub-directory %s not found in archive' % subdir)
		zipFile.extractall(targetBaseDir, names)
		zipFile.close()
	elif archiveFile.split('/')[-1].split('.')[-1] == 'xz':
		ensureCommandIsAvailable('xz')
		Popen(['xz', '-f', '-d', '-k', archiveFile]).wait()
		tar = archiveFile[:-3]
		if tarfile.is_tarfile(tar):
			tarFile = tarfile.open(tar, 'r')
			members = None
			if subdir:
				if not subdir.endswith('/'):
					subdir += '/'
				members = [
					member for member in tarFile.getmembers()
					if member.name.startswith(subdir)
				]
				if not members:
					sysExit('sub-directory %s not found in archive' % subdir)
			tarFile.extractall(targetBaseDir)
			tarFile.close()
	else:
		sysExit('Unrecognized archive type in file '
				+ archiveFile)
开发者ID:dnivra,项目名称:haikuporter,代码行数:51,代码来源:Utils.py

示例9: _extract

    def _extract(self, filename):
        """ extractor helper
        """
        try:
            file_type = self._get_file_type(filename)
            opener = mode = None

            if file_type == 'zip':
                opener, mode = zipfile.ZipFile, 'r'

            elif file_type == 'gz':
                if tarfile.is_tarfile(filename):
                    opener, mode = tarfile.open, 'r:gz'

            elif file_type == 'bz2':
                if tarfile.is_tarfile(filename):
                    opener, mode = tarfile.open, 'r:bz2'

            if not opener:
                raise Exception("Unsupported file compression")

            cfile = opener(filename, mode)

            # if first member is dir, skip 1st container path
            if file_type == 'zip':
                members = cfile.namelist()
            else:
                members = cfile.getmembers()

            stdout = ''
            for member in members:
                if file_type == 'zip':
                    member_name = member
                else:
                    member_name = member.name

                stdout += "Extracted " + member_name + "\n"
            cfile.extractall(self.working_dir)
            cfile.close()

        except Exception as e:
            try:
                return self._extract_alternative(filename)
            except:
                raise Exception("Could not extract file: %s" % e)

        ret = {'out': 0, 'stderr': '', 'stdout': stdout}
        return ret
开发者ID:arindamchoudhury,项目名称:ecm-agent,代码行数:48,代码来源:plugin_source.py

示例10: archive_open

def archive_open(name):
    if tarfile.is_tarfile(name):
        return tarfile.open(name)
    elif zipfile.is_zipfile(name):
        return zipfile.ZipFile(name)
    else:
        return None
开发者ID:ConPaaS-team,项目名称:conpaas,代码行数:7,代码来源:misc.py

示例11: setup_buffer

 def setup_buffer(self):
     if self.exists == False:
         return None
     if self.subfile == None:
         # assume a regular file or gzipped
         filename, file_extension = os.path.splitext(self.fname)
         if file_extension == '.gzip' or file_extension == '.gz':
             import gzip
             try:
                 self.buffer = gzip.open(self.fname, 'r')
                 self.is_gzip = True
             except:
                 pass
                 #print >> sys.stderr,'[e] bad gzip file?',self.fname
         else:
             self.buffer = self.fname
     else:
         import tarfile
         if tarfile.is_tarfile(self.fname):
             self.tarfile = tarfile.open(self.fname, "r:gz")
             try:
                 tarinfo = self.tarfile.getmember(self.subfile)
             except:
                 print >> sys.stderr,'[e] file in archive not found:',self.subfile
                 tarinfo = None
                 self.buffer = None
             if tarinfo != None:
                 if tarinfo.isreg():
                     self.buffer = self.tarfile.extractfile(tarinfo)
                 else:
                     self.buffer = None
         else:
             self.buffer = None
开发者ID:matplo,项目名称:pylhe,代码行数:33,代码来源:__init__.py

示例12: read_packages

	def read_packages(self):
		print("Reading {0}...".format(self._cache_db), end="", flush=True)

		if not os.path.exists(self._cache_db):
			print(" not found!")
			return False
		if not tarfile.is_tarfile(self._cache_db):
			print(" not a tar!")
			return False

		tar = tarfile.open(self._cache_db)
		pkg_info = {}
		self._pkgs = {}

		for info in tar.getmembers():
			if not info.isfile():
				continue

			( binpkg_name, file_name ) = info.name.split("/")

			pi = pkg_info.get(binpkg_name, {})
			with tar.extractfile(info) as file:
				pi[file_name] = [x.decode("utf-8").rstrip() for x in file.readlines()]

			if len(pi.keys() & { "desc", "depends" }) == 2:
				BinaryRepo.BinPkg(self, pi["desc"], pi["depends"])
				del pkg_info[binpkg_name]
				continue

			pkg_info[binpkg_name] = pi

		if len(pkg_info) != 0:
			raise Exception("Incomplete packages in DB")

		print(" done")
开发者ID:Arch-Linux-MIPS,项目名称:architect,代码行数:35,代码来源:binaryrepo.py

示例13: archive_get_type

def archive_get_type(name):
    if tarfile.is_tarfile(name):
        return 'tar'
    elif zipfile.is_zipfile(name):
        return 'zip'
    else:
        return None
开发者ID:ConPaaS-team,项目名称:conpaas,代码行数:7,代码来源:misc.py

示例14: is_tar

 def is_tar(path, file):
     try:
         if tarfile.is_tarfile(os.path.join(path, file)):
             return True
     except OSError, e:
         logging.error("Error in is_tar for '%s': %s" % (file, e))
         raise OSError
开发者ID:bl4ckh0l3z,项目名称:droidtrail,代码行数:7,代码来源:utils.py

示例15: unarchive

def unarchive(archive_path, dest):
    """Extract the contents of a tar or zip file at *archive_path* into the
    directory *dest*.

    :type archive_path: str
    :param archive_path: path to archive file
    :type dest: str
    :param dest: path to directory where archive will be extracted

    *dest* will be created if it doesn't already exist.

    tar files can be gzip compressed, bzip2 compressed, or uncompressed. Files
    within zip files can be deflated or stored.
    """
    if tarfile.is_tarfile(archive_path):
        with contextlib.closing(tarfile.open(archive_path, 'r')) as archive:
            archive.extractall(dest)
    elif zipfile.is_zipfile(archive_path):
        with contextlib.closing(zipfile.ZipFile(archive_path, 'r')) as archive:
            for name in archive.namelist():
                # the zip spec specifies that front slashes are always
                # used as directory separators
                dest_path = os.path.join(dest, *name.split('/'))

                # now, split out any dirname and filename and create
                # one and/or the other
                dirname, filename = os.path.split(dest_path)
                if dirname and not os.path.exists(dirname):
                    os.makedirs(dirname)
                if filename:
                    with open(dest_path, 'wb') as dest_file:
                        dest_file.write(archive.read(name))
    else:
        raise IOError('Unknown archive type: %s' % (archive_path,))
开发者ID:bchess,项目名称:mrjob,代码行数:34,代码来源:util.py


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