本文整理汇总了Python中tarfile.TarFile.close方法的典型用法代码示例。如果您正苦于以下问题:Python TarFile.close方法的具体用法?Python TarFile.close怎么用?Python TarFile.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tarfile.TarFile
的用法示例。
在下文中一共展示了TarFile.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_archive
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def create_archive(self):
(handle, path) = mkstemp(dir=self.temp_dir)
os.close(handle)
archive = TarFile(path, mode="w")
archive.add(os.path.join(_common.RSRC, "full.mp3"), "full.mp3")
archive.close()
return path
示例2: _createScriptExtensionTarArchive
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def _createScriptExtensionTarArchive(self, sourceDirectory, scriptExtensionName):
""" Creates a TAR archive for the given script extension. """
tarFileName = scriptExtensionName + ".tar"
tarFilePath = os.path.join(self.__buildConfiguration.distDirectory, tarFileName)
tarFile = TarFile(tarFilePath, "w")
for inputDirectory in ["lib", "src"]:
baseDirectory = os.path.join(sourceDirectory, inputDirectory)
if os.path.exists(baseDirectory):
for packageDirName in os.listdir(baseDirectory):
pythonModulesToAddList = list()
packageDirectory = os.path.join(baseDirectory, packageDirName)
if os.path.exists(packageDirectory):
for walkTuple in os.walk(packageDirectory):
directoryPath = walkTuple[0]
fileNameList = walkTuple[2]
for fileName in fileNameList:
if fileName.endswith(".py") or fileName == "SCRIPTS":
filePath = os.path.join(directoryPath, fileName)
pythonModulesToAddList.append(filePath)
for pythonModule in pythonModulesToAddList:
startPosition = pythonModule.find(baseDirectory) + len(baseDirectory) + 1
archiveName = pythonModule[startPosition:]
tarFile.add(pythonModule, archiveName)
tarFile.close()
if self.verbose:
print("Created tar archive '%s'." % tarFilePath)
示例3: move_certs
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def move_certs(self, paths):
self.log.info("Staging internal ssl certs for %s", self._log_name)
yield self.pull_image(self.move_certs_image)
# create the volume
volume_name = self.format_volume_name(self.certs_volume_name, self)
# create volume passes even if it already exists
self.log.info("Creating ssl volume %s for %s", volume_name, self._log_name)
yield self.docker('create_volume', volume_name)
# create a tar archive of the internal cert files
# docker.put_archive takes a tarfile and a running container
# and unpacks the archive into the container
nb_paths = {}
tar_buf = BytesIO()
archive = TarFile(fileobj=tar_buf, mode='w')
for key, hub_path in paths.items():
fname = os.path.basename(hub_path)
nb_paths[key] = '/certs/' + fname
with open(hub_path, 'rb') as f:
content = f.read()
tarinfo = TarInfo(name=fname)
tarinfo.size = len(content)
tarinfo.mtime = os.stat(hub_path).st_mtime
tarinfo.mode = 0o644
archive.addfile(tarinfo, BytesIO(content))
archive.close()
tar_buf.seek(0)
# run a container to stage the certs,
# mounting the volume at /certs/
host_config = self.client.create_host_config(
binds={
volume_name: {"bind": "/certs", "mode": "rw"},
},
)
container = yield self.docker('create_container',
self.move_certs_image,
volumes=["/certs"],
host_config=host_config,
)
container_id = container['Id']
self.log.debug(
"Container %s is creating ssl certs for %s",
container_id[:12], self._log_name,
)
# start the container
yield self.docker('start', container_id)
# stage the archive to the container
try:
yield self.docker(
'put_archive',
container=container_id,
path='/certs',
data=tar_buf,
)
finally:
yield self.docker('remove_container', container_id)
return nb_paths
示例4: reader
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def reader(self):
"""Package up filesystem contents as a tarball."""
result = BytesIO()
tarball = TarFile(fileobj=result, mode="w")
for child in self.path.children():
tarball.add(child.path, arcname=child.basename(), recursive=True)
tarball.close()
result.seek(0, 0)
yield result
示例5: download
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def download(self):
"""
Ein Download wird ausgeführt
"""
self.init2() # Basisklasse einrichten
simulation = self.request.POST.get("simulation", False)
self._setup_path()
if simulation:
self.request.echo("<h1>Download Simulation!</h1><pre>")
self.request.echo("request path: %s\n" % self.request_path)
log_typ = "download simulation start"
else:
log_typ = "download start"
self.db.log(log_typ, self.context['request_path'])
artist = self.request.POST.get("artist", "")
album = self.request.POST.get("album", "")
files, _ = self._read_dir()
args = {"prefix": "PyDown_%s_" % self.request.environ["REMOTE_USER"]}
if self.request.cfg["temp"]:
args["dir"] = self.request.cfg["temp"]
temp = NamedTemporaryFile(**args)
tar = TarFile(mode="w", fileobj=temp)
if simulation:
self.request.write("-"*80)
self.request.write("\n")
for file_info in files:
filename = file_info[0]
abs_path = posixpath.join(self.request_path, filename)
arcname = posixpath.join(artist, album, filename)
if simulation:
#~ self.request.write("absolute path..: %s\n" % abs_path)
self.request.write("<strong>%s</strong>\n" % arcname)
try:
tar.add(abs_path, arcname)
except IOError, e:
self.request.write("<h1>Error</h1><h2>Can't create archive: %s</h2>" % e)
try:
tar.close()
except:
pass
try:
temp.close()
except:
pass
return
示例6: write_tar
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def write_tar(filename):
from tarfile import TarFile
try:
tf = TarFile(filename, 'w')
logger.debug('Writing tar archive to %s' % filename)
_write_files_to_archive(tf.add, files)
tf.close()
logger.debug('Completed tar archive size is %i' % os.stat(filename).st_size)
except IOError as ex:
logger.warn("I/O error({0}) while writing tar archive: {1}".format(e.errno, e.strerror))
os.unlink(filename)
finally:
tf.close()
示例7: _check_tar_file
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def _check_tar_file(self, content, rootdir, datafiles,
simpleNames=False, noTxt=False):
with NamedTemporaryFile('w') as tempfile:
tempfile.write(content)
tempfile.flush()
if getsize(tempfile.name) > 0:
expect(is_tarfile(tempfile.name)).to_be_truthy()
try:
tf = TarFile(tempfile.name, 'r')
self._check_names(datafiles, tf.getnames(),
rootdir, simpleNames, noTxt)
finally:
tf.close()
else:
self._check_names(datafiles, [],
rootdir, simpleNames, noTxt)
示例8: load_from_file
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def load_from_file(self, f):
tar = TarFile(f, "r")
# load info file
f = tar.extractfile("info.py")
self.agedesc, self.generation = eval(f.read(-1), {"__builtins__": None})
f.close()
# load agents
for info in tar.getmembers():
if (splitext(info.name)[1]==".agt" and info.isfile()):
f = tar.extractfile(info)
self.add(Agent(self.agedesc, file = f))
f.close()
tar.close()
示例9: _check_tar_file
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def _check_tar_file(self, content, rootdir, datafiles,
simpleNames=False, noTxt=False):
with NamedTemporaryFile('w') as tempfile:
for c in content:
tempfile.write(c)
tempfile.flush()
if getsize(tempfile.name) > 0:
self.assertTrue(is_tarfile(tempfile.name))
try:
tf = TarFile(tempfile.name, 'r')
self._check_names(datafiles, tf.getnames(),
rootdir, simpleNames, noTxt)
finally:
tf.close()
else:
self._check_names(datafiles, [],
rootdir, simpleNames, noTxt)
示例10: run
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def run(self, args, argv):
# Create a temporary tarball with our whole build context and
# dockerfile for the update
tmp = tempfile.NamedTemporaryFile(suffix="dckr.tar.gz")
tmp_tar = TarFile(fileobj=tmp, mode='w')
# Add the executable to the tarball, using the current
# configured binfmt_misc path. If we don't get a path then we
# only need the support libraries copied
ff, enabled = _check_binfmt_misc(args.executable)
if not enabled:
print("binfmt_misc not enabled, update disabled")
return 1
if ff:
tmp_tar.add(args.executable, arcname=ff)
# Add any associated libraries
libs = _get_so_libs(args.executable)
if libs:
for l in libs:
tmp_tar.add(os.path.realpath(l), arcname=l)
# Create a Docker buildfile
df = StringIO()
df.write("FROM %s\n" % args.tag)
df.write("ADD . /\n")
df.seek(0)
df_tar = TarInfo(name="Dockerfile")
df_tar.size = len(df.buf)
tmp_tar.addfile(df_tar, fileobj=df)
tmp_tar.close()
# reset the file pointers
tmp.flush()
tmp.seek(0)
# Run the build with our tarball context
dkr = Docker()
dkr.update_image(args.tag, tmp, quiet=args.quiet)
return 0
示例11: save_to_file
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def save_to_file(self, f):
tar = TarFile(f, "w")
# save info file
f = StringIO(repr((self.agedesc, self.generation)))
info = tar.gettarinfo(None, "info.py", f)
tar.addfile(info, f)
f.close()
# save agents
for i in range(len(self.agents)):
f = StringIO()
self.agents[i].save_to_file(f)
info = tar.gettarinfo(None, str(i)+".agt", f)
tar.addfile(info, f)
f.close()
tar.close()
示例12: optional_extract
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def optional_extract(self, output, tarname):
"""Extracts test repository data if needed
Checks whether directory exists or is older than archive.
"""
tarname = get_test_file(tarname)
if (not os.path.exists(output) or
os.path.getmtime(output) < os.path.getmtime(tarname)):
# Remove directory if outdated
if os.path.exists(output):
shutil.rmtree(output)
# Extract new content
tar = TarFile(tarname)
tar.extractall(settings.DATA_DIR)
tar.close()
# Update directory timestamp
os.utime(output, None)
示例13: run
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def run(self, args, argv):
# Create a temporary tarball with our whole build context and
# dockerfile for the update
tmp = tempfile.NamedTemporaryFile(suffix="dckr.tar.gz")
tmp_tar = TarFile(fileobj=tmp, mode='w')
# Add the executable to the tarball
bn = os.path.basename(args.executable)
ff = "/usr/bin/%s" % bn
tmp_tar.add(args.executable, arcname=ff)
# Add any associated libraries
libs = _get_so_libs(args.executable)
if libs:
for l in libs:
tmp_tar.add(os.path.realpath(l), arcname=l)
# Create a Docker buildfile
df = StringIO()
df.write("FROM %s\n" % args.tag)
df.write("ADD . /\n")
df.seek(0)
df_tar = TarInfo(name="Dockerfile")
df_tar.size = len(df.buf)
tmp_tar.addfile(df_tar, fileobj=df)
tmp_tar.close()
# reset the file pointers
tmp.flush()
tmp.seek(0)
# Run the build with our tarball context
dkr = Docker()
dkr.update_image(args.tag, tmp, quiet=args.quiet)
return 0
示例14: reader
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def reader(self, remote_snapshots=None):
"""
Package up filesystem contents as a tarball.
"""
result = BytesIO()
tarball = TarFile(fileobj=result, mode="w")
for child in self.path.children():
tarball.add(child.path, arcname=child.basename(), recursive=True)
tarball.close()
# You can append anything to the end of a tar stream without corrupting
# it. Smuggle some data about the snapshots through here. This lets
# tests verify that an incremental stream is really being produced
# without forcing us to implement actual incremental streams on top of
# dumb directories.
if remote_snapshots:
result.write(
u"\nincremental stream based on\n{}".format(
u"\n".join(snapshot.name for snapshot in remote_snapshots)
).encode("ascii")
)
result.seek(0, 0)
yield result
示例15: test_can_put_extracted_file_from_tar
# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import close [as 别名]
def test_can_put_extracted_file_from_tar(self):
tempdir = self.make_tempdir()
tarname = os.path.join(tempdir, "mytar.tar")
filename = os.path.join(tempdir, "foo")
# Set up a file to add the tarfile.
with open(filename, "w") as f:
f.write("bar")
# Setup the tar file by adding the file to it.
# Note there is no context handler for TarFile in python 2.6
try:
tar = TarFile(tarname, "w")
tar.add(filename, "foo")
finally:
tar.close()
# See if an extracted file can be uploaded to s3.
try:
tar = TarFile(tarname, "r")
with closing(tar.extractfile("foo")) as f:
self.assert_can_put_object(body=f)
finally:
tar.close()