本文整理汇总了Python中zipfile.BadZipFile方法的典型用法代码示例。如果您正苦于以下问题:Python zipfile.BadZipFile方法的具体用法?Python zipfile.BadZipFile怎么用?Python zipfile.BadZipFile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zipfile
的用法示例。
在下文中一共展示了zipfile.BadZipFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _read_meta
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _read_meta(source) -> Tuple[ZipFile, PluginMeta]:
try:
file = ZipFile(source)
data = file.read("maubot.yaml")
except FileNotFoundError as e:
raise MaubotZipMetaError("Maubot plugin not found") from e
except BadZipFile as e:
raise MaubotZipMetaError("File is not a maubot plugin") from e
except KeyError as e:
raise MaubotZipMetaError("File does not contain a maubot plugin definition") from e
try:
meta_dict = yaml.load(data)
except (YAMLError, KeyError, IndexError, ValueError) as e:
raise MaubotZipMetaError("Maubot plugin definition file is not valid YAML") from e
try:
meta = PluginMeta.deserialize(meta_dict)
except SerializerError as e:
raise MaubotZipMetaError("Maubot plugin definition in file is invalid") from e
return file, meta
示例2: extract_template
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def extract_template(package_path):
print("package_path" + package_path)
root_path = os.path.join(tempfile.gettempdir(), "salesforcexytools")
try:
zfile = zipfile.ZipFile(package_path, 'r')
for filename in zfile.namelist():
if filename.endswith('/'): continue
if filename.endswith('.py'): continue
if filename.startswith("templates/"):
f = os.path.join(root_path, filename)
if not os.path.exists(os.path.dirname(f)):
os.makedirs(os.path.dirname(f))
with open(f, "wb") as fp:
fp.write(zfile.read(filename))
except zipfile.BadZipFile as ex:
print(str(ex))
return
示例3: _loadMetadata
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _loadMetadata(file_name: str) -> Dict[str, Dict[str, Any]]:
result = dict() # type: Dict[str, Dict[str, Any]]
try:
archive = zipfile.ZipFile(file_name, "r")
except zipfile.BadZipFile:
Logger.logException("w", "Unable to retrieve metadata from {fname}: 3MF archive is corrupt.".format(fname = file_name))
return result
metadata_files = [name for name in archive.namelist() if name.endswith("plugin_metadata.json")]
for metadata_file in metadata_files:
try:
plugin_id = metadata_file.split("/")[0]
result[plugin_id] = json.loads(archive.open("%s/plugin_metadata.json" % plugin_id).read().decode("utf-8"))
except Exception:
Logger.logException("w", "Unable to retrieve metadata for %s", metadata_file)
return result
示例4: extract_zip
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def extract_zip(filename: str, destination_dir: str):
""" Extracts a zipped file
Parameters
----------
filename : str
The zipped filename
destination_dir : str
The directory where the zipped will be placed
"""
msg_printer = Printer()
try:
with msg_printer.loading(f"Unzipping file {filename} to {destination_dir}"):
stdout.flush()
with zipfile.ZipFile(filename, "r") as z:
z.extractall(destination_dir)
msg_printer.good(f"Finished extraction {filename} to {destination_dir}")
except zipfile.BadZipFile:
msg_printer.fail(f"Couldnot extract {filename} to {destination_dir}")
示例5: test_empty_zipfile
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_empty_zipfile(self):
# Check that creating a file in 'w' or 'a' mode and closing without
# adding any files to the archives creates a valid empty ZIP file
zipf = zipfile.ZipFile(TESTFN, mode="w")
zipf.close()
try:
zipf = zipfile.ZipFile(TESTFN, mode="r")
except zipfile.BadZipFile:
self.fail("Unable to create empty ZIP file in 'w' mode")
zipf = zipfile.ZipFile(TESTFN, mode="a")
zipf.close()
try:
zipf = zipfile.ZipFile(TESTFN, mode="r")
except:
self.fail("Unable to create empty ZIP file in 'a' mode")
示例6: test_read_with_bad_crc
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_read_with_bad_crc(self):
"""Tests that files with bad CRCs raise a BadZipFile exception when read."""
zipdata = self.zip_with_bad_crc
# Using ZipFile.read()
with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
# Using ZipExtFile.read()
with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
with zipf.open('afile', 'r') as corrupt_file:
self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
# Same with small reads (in order to exercise the buffering logic)
with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
with zipf.open('afile', 'r') as corrupt_file:
corrupt_file.MIN_READ_SIZE = 2
with self.assertRaises(zipfile.BadZipFile):
while corrupt_file.read(2):
pass
示例7: import_has_conflicts
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def import_has_conflicts(archive):
"""Verify if the `archive` files conflicts with the user presets.
:param archive: path of the archive to analyze
:type archive: str
:rtype: bool
"""
try:
with ZipFile(archive) as archive:
for member in archive.namelist():
if preset_exists(member):
return True
except(OSError, BadZipFile) as e:
raise PresetImportError(str(e))
return False
示例8: import_conflicts
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def import_conflicts(archive):
"""Return a list of conflicts between `archive` files and user presets.
:param archive: path of the archive to analyze
:type archive: str
"""
conflicts = []
try:
with ZipFile(archive) as archive:
for member in archive.namelist():
if preset_exists(member):
conflicts.append(member)
except(OSError, BadZipFile) as e:
raise PresetImportError(str(e))
return conflicts
示例9: _getPluginIdFromFile
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _getPluginIdFromFile(self, filename: str) -> Optional[str]:
plugin_id = None
try:
with zipfile.ZipFile(filename, "r") as zip_ref:
for file_info in zip_ref.infolist():
if file_info.filename.endswith("/"):
plugin_id = file_info.filename.strip("/")
break
except zipfile.BadZipFile:
Logger.logException("e", "Failed to load plug-in file. The zip archive seems to be corrupt.")
return None # Signals that loading this failed.
except FileNotFoundError:
Logger.logException("e", "Failed to load plug-in file as we were unable to find it.")
return None # Signals that loading this failed.
return plugin_id
# Returns a list of all possible plugin ids in the plugin locations:
示例10: getPackageLicense
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def getPackageLicense(self, filename: str) -> Optional[str]:
license_string = None
def is_license(zipinfo: zipfile.ZipInfo) -> bool:
return os.path.basename(zipinfo.filename).startswith("LICENSE")
try:
with zipfile.ZipFile(filename) as archive:
# Go through all the files and use the first successful read as the result
license_files = sorted(filter(is_license, archive.infolist()), key = lambda x: len(x.filename)) # Find the one with the shortest path.
for file_info in license_files:
Logger.log("d", "Found potential license file '{filename}'".format(filename = file_info.filename))
try:
with archive.open(file_info.filename, "r") as f:
data = f.read()
license_string = data.decode("utf-8")
break
except:
Logger.logException("e", "Failed to load potential license file '%s' as text file.", file_info.filename)
license_string = None
except zipfile.BadZipFile as e:
Logger.error("Package is corrupt: {err}".format(err = str(e)))
license_string = None
except UnicodeDecodeError:
Logger.error("Package filenames are not UTF-8 encoded! Encoding unknown.")
license_string = None
return license_string
示例11: read_sheets
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def read_sheets(self):
try:
self.workbook = openpyxl.load_workbook(self.input_name, data_only=True)
except BadZipFile as e: # noqa
# TODO when we have python3 only add 'from e' to show exception chain
raise BadXLSXZipFile(
"The supplied file has extension .xlsx but isn't an XLSX file."
)
self.sheet_names_map = OrderedDict(
(sheet_name, sheet_name) for sheet_name in self.workbook.sheetnames
)
if self.include_sheets:
for sheet in list(self.sheet_names_map):
if sheet not in self.include_sheets:
self.sheet_names_map.pop(sheet)
for sheet in self.exclude_sheets or []:
self.sheet_names_map.pop(sheet, None)
sheet_names = list(sheet for sheet in self.sheet_names_map.keys())
self.sub_sheet_names = sheet_names
self.configure_sheets()
示例12: test_open_corrupt_container
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def test_open_corrupt_container(self):
with self.assertRaises(FileNotFoundError):
DataContainer('test-container.data.zip')
with open("test-container.data.zip", "w+") as f:
f.write("INVALID_ZIP_DATA")
with self.assertRaises(zipfile.BadZipFile):
DataContainer('test-container.data.zip')
os.unlink('test-container.data.zip')
with zipfile.ZipFile('test-container.data.zip', 'w') as f:
f.writestr('bad.txt', 'BAD')
with self.assertRaises(MetadataNotFoundError):
DataContainer('test-container.data.zip')
os.unlink('test-container.data.zip')
示例13: _process_md5
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def _process_md5(md5: str) -> bool:
"""Download the given file from CarbonBlack and upload to S3, returning True if successful."""
try:
binary = CARBON_BLACK.select(Binary, md5)
_upload_to_s3(binary)
return True
except zipfile.BadZipFile:
LOGGER.exception('[BadZipFile] Error downloading %s', md5)
LOGGER.info('This md5 is invalid and will not retried')
return False
except (BotoCoreError, ServerError):
LOGGER.exception('Error downloading %s', md5)
LOGGER.error(
'A temporary error was encountered during downloading. This md5 will be '
'retried at a later time.'
)
raise
except ObjectNotFoundError:
LOGGER.exception('Error downloading %s', md5)
LOGGER.info(
'This may be caused due to a race condition where the requested binary is not yet '
'available for download from the server. This binary will be retried at a later time.'
)
raise
示例14: get_apk_id
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def get_apk_id(apkfile):
"""Extract identification information from APK.
Androguard is preferred since it is more reliable and a lot
faster. Occasionally, when androguard can't get the info from the
APK, aapt still can. So aapt is also used as the final fallback
method.
:param apkfile: path to an APK file.
:returns: triplet (appid, version code, version name)
"""
if use_androguard():
try:
return get_apk_id_androguard(apkfile)
except zipfile.BadZipFile as e:
logging.error(apkfile + ': ' + str(e))
if 'aapt' in config:
return get_apk_id_aapt(apkfile)
else:
return get_apk_id_aapt(apkfile)
示例15: unzip_archive
# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import BadZipFile [as 别名]
def unzip_archive(archive_path):
if os.path.exists(archive_path):
set_import_status('Unzipping model')
import zipfile
try:
zip_ref = zipfile.ZipFile(archive_path, 'r')
extract_dir = os.path.dirname(archive_path)
zip_ref.extractall(extract_dir)
zip_ref.close()
except zipfile.BadZipFile:
print('Error when dezipping file')
os.remove(archive_path)
print('Invaild zip. Try again')
set_import_status('')
return None, None
gltf_file = os.path.join(extract_dir, 'scene.gltf')
return gltf_file, archive_path
else:
print('ERROR: archive doesn\'t exist')