コード例 #1
0
    def set_mode(self, mode):

        def access_file(f):
            with zipfile.ZipFile(self.path, 'r') as archive:
                return f(archive)

        def access_raw(f):
            return f(self.archive)

        def access_lock(f):
            exception = None
            while True:
                try: # workaround for BadZipFile in multiprocessing mode
                    with self.lock:
                        with self.tlock:
                            return f(self.archive)
                except Exception as e:
                    if False:
                        sys.stdout.write(f"\rZipFileSource {os.path.basename(self.path)} read error, falling back to 'file' mode{' ' * 10}")
                        sys.stdout.flush()
                    try:
                        if self.archive is not None:
                            self.archive.close()
                            self.archive = None
                        self.files, self.time_of_issues, self.timestamps, self.nb_data_per_pkl_file = self.get_files(access_file)
                        rv =  access_file(f)
                        self.archive = zipfile.ZipFile(self.path, 'r')
                        return rv

                    except Exception as access_file_e:
                        self.archive = zipfile.ZipFile(self.path, 'r')
                        print(f'\rZipFileSource fallback failed: {access_file_e}, retrying infinitely')
                        time.sleep(0.1)

        if mode == "lock":
            self.archive = zipfile.ZipFile(self.path, 'r')
            self.access = access_lock
        elif mode == "file":
            self.archive = None
            self.access = access_file
        elif mode == "none":
            self.archive = zipfile.ZipFile(self.path, 'r')
            self.access = access_raw
コード例 #2
0
ファイル: app.py プロジェクト: ysfchn/AI-Kit
def repairaia(aia_path='../sample.aia'):
    """
    Repair .aia.

    - Fixes "project in project" error.
    """
    will_deleted = list()

    print("Repairing project...")
    zip_file = zipfile.ZipFile(aia_path, 'r')
    # Checks the "project in project" situation and adds the all unwanted file
    # names to a list.
    # ...for example Screen files in the assets folder are unexpected.
    for file_name in zip_file.namelist():
        if file_name.startswith(
            ("assets/external_comps/assets/external_comps/",
             "assets/external_comps/src/",
             "assets/external_comps/youngandroidproject/")):

            will_deleted.append(file_name)
            print("[-] - DELETED: " + file_name)
        # It is not needed to store .aia files as assets too.
        elif file_name.endswith(".aia"):
            will_deleted.append(file_name)
            print("[-] - DELETED: " + file_name)

    # Delete unwanted files from the .aia file.
    delete_from_zip_file(aia_path, file_names=will_deleted)

    # If will_deleted list is empty, this means there is nothing to edit.
    if will_deleted == list():
        print("Nothing found to repair.")

    print("")
    print("[#] Repair finished. Affected files: " + str(len(will_deleted)))
    zip_file.close()
    return True
コード例 #3
0
ファイル: zip.py プロジェクト: leddartech/pioneer.common
 def reopen(self, mode='a'):
     if not self.is_opened:
         self.archive = zipfile.ZipFile(self.filepath, mode=mode)
         self.is_opened = True
コード例 #4
0
ファイル: zip.py プロジェクト: leddartech/pioneer.common
 def __init__(self, filepath, mode='w'):
     self.filepath = filepath
     self.archive = zipfile.ZipFile(self.filepath, mode=mode)
     self.is_opened = True
コード例 #5
0
 def access_file(f):
     with zipfile.ZipFile(self.path, 'r') as archive:
         return f(archive)
コード例 #6
0
ファイル: app.py プロジェクト: ysfchn/AI-Kit
def cleanaia(aia_path='../sample.aia'):
    """
    Clean-up the .aia.

    - Scans the .bky and .scm files, and deletes all assets which is not refere
    nced in these files.
    """
    will_deleted = list()
    print("Cleaning the project...")
    zip_file = zipfile.ZipFile(aia_path, 'r')

    # Content of all .bky files in project.
    bky = list()

    # Content of all .scm files in project.
    scm = list()

    # Content of the project.properties file.
    prop = ""

    # Reads .bky, .scm and project.properties files from project and saves into
    # a variable.
    for file_name in zip_file.namelist():
        if file_name.endswith(".bky"):
            bky.append(zip_file.read(file_name).decode(sys.stdout.encoding))
        elif file_name.endswith(".scm"):
            scm.append(zip_file.read(file_name).decode(sys.stdout.encoding))
        elif "project.properties" in file_name:
            prop = prop + zip_file.read(file_name).decode(sys.stdout.encoding)

    # Converts list to string for checking the references.
    filebky = "".join(bky)
    filescm = "".join(scm)

    for file_name in zip_file.namelist():
        # Gets the name of the file by deleting the path piece.
        name = file_name.split("/")[-1]
        if file_name.startswith("assets/") and \
                "external_comps/" not in file_name:
            # Checks if the name is already used in project files.
            if name in filebky:
                pass
            elif name in filescm:
                pass
            elif name in prop:
                pass
            else:
                will_deleted.append(file_name)
                print("DELETED: " + file_name)

    # Delete unwanted files from the .aia file.
    delete_from_zip_file(aia_path, file_names=will_deleted)

    # If will_deleted list is empty, this means there is nothing to edit.
    if will_deleted == list():
        print("Nothing found to cleanup.")

    print("")
    print("[#] Cleanup finished. Affected files: " + str(len(will_deleted)))
    zip_file.close()
    return True
コード例 #7
0
for filename in files:
    #print(filename)
    newfile = os.path.normpath(os.path.join(reducedDir, filename))
    newDir = os.path.dirname(newfile)

    if os.path.isdir(filename):
        continue

    if not os.path.exists(newDir):
        os.makedirs(newDir)

    print("Processing", filename)

    if filename.endswith('epub'):
        zin = zipfile.ZipFile(filename, 'r')
        zout = zipfile.ZipFile(newfile, 'w')
        for item in zin.infolist():
            buffer = zin.read(item.filename)
            if (item.filename[-4:] != '.ttf') and (item.filename[-4:] !=
                                                   '.otf'):
                zout.writestr(item, buffer)
        zout.close()
        zin.close()
    else:
        shutil.copy2(filename, newfile)

#filename = '682000733.epub'
#zipfile.delete_from_zip_file(filename, pattern='.*.ttf')

# import subprocess