Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect whether zlib is available and whether ZIP_DEFLATED is available?

Tags:

python

zlib

The zipfile.ZipFile documentation says that ZIP_DEFLATED can be used as compression method only if zlib is available, but neither zipfile module specification nor zlib module specification says anything about when zlib might not be available, or how to check for its availability.

I work on Windows and when I install any version of Python, zlib module is available. Is this different in Linux? Does zlib need to be installed separately?

Also, what is the proper way to check for zlib availability? Is import zlib going to raise an ImportError if it is not available?

In oher words, is this the correct way to use zipfile?

try:
    import zlib
except ImportError:
    zlib = None

compression = zipfile.ZIP_STORED if zlib is None else zipfile.ZIP_DEFLATED

with zipfile.ZipFile(file, mode, compression) as zf:
    ...
like image 318
zvone Avatar asked Jul 21 '20 10:07

zvone


1 Answers

  • On Ubuntu if you install Python 3 using apt, e.g. sudo apt install python3.8, zlib will be installed as a dependency.
  • Another way is to install Python 3 from source code. In this case, you need to install all prerequisites, including zlib1g-dev, (and this action is sometimes forgotten to do) and then compile and install python as sudo make install. Full instructions here
  • Yes, if zlib is not available import zlib will raise exception, such as
>>> import zlib 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'zlib

There are examples of code like this in the Python standard library. e.g. in zipfile.py:

try:
    import zlib # We may need its compression method
    crc32 = zlib.crc32
except ImportError:
    zlib = None
    crc32 = binascii.crc32
like image 187
alex_noname Avatar answered Oct 01 '22 19:10

alex_noname