'How do cancel an operation(unzip) in a few seconds in Python?

Some files do not know what they are from have long extract For example, if it is not extracted for 60 seconds or the time is passed, I want to delete the original file to cancel the operation.

import pyzipper
with pyzipper.AESZipFile('test.zip', 'r', compression=pyzipper.ZIP_LZMA, encryption=pyzipper.WZ_AES) as extracted_zip:
    extracted_zip.extractall(pwd=str.encode("@apkclub"))
    os.remove(test.zip)


Solution 1:[1]

You should iterate through files inside the archive and read them in chunks. I didn't test this code but the correct solution could be close to:

import os
import time
import pyzipper


CHUNK_SIZE = '4096'

zip_fname = 'test.zip'

try:
    with pyzipper.AESZipFile(zip_fname, 'r', compression=pyzipper.ZIP_LZMA, encryption=pyzipper.WZ_AES) as zip_file:
        for filename in zip_file.namelist():
            start_time = time.time()
            with zip_file.open(filename) as file_in_archive:
                with open(filename, 'w+') as extracted_file:
                    while (chunk := file_in_archive.read(CHUNK_SIZE)):
                        extracted_file.write(chunk)
                        if time.time() - start_time > 60:
                            raise Exception('too long')
except Exception as error:
    print(error)

os.remove(zip_fname)

You may want to implement more sophisticated logic in handling the timeout situation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1