Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 equivalent of importlib.machinery.EXTENSION_SUFFIXES

I want to use importlib.machinery.EXTENSION_SUFFIXES from Python 3 but am unfortunately using Python 2.7.

EXTENSION_SUFFIXES evaluates to ['.cpython-34m-x86_64-linux-gnu.so', '.cpython-34m.so', '.abi3.so', '.so'], but this is specific to my machine and possibly python version, so I cannot simply hardcode the list.

Here's where EXTENSION_SUFFIXES is built in Python 3's source: https://github.com/python/cpython/blob/3.6/Lib/importlib/_bootstrap_external.py#L1431. However it seems to go down into the C implementation (link), so it's unclear to me how I can get this info.

How can I obtain this list in Python 2.7?

like image 218
ty. Avatar asked Dec 07 '25 08:12

ty.


1 Answers

Use imp.get_suffixes() instead:

Return a list of 3-element tuples, each describing a particular type of module. Each triple has the form (suffix, mode, type), where suffix is a string to be appended to the module name to form the filename to search for, mode is the mode string to pass to the built-in open() function to open the file (this can be 'r' for text files or 'rb' for binary files), and type is the file type, which has one of the values PY_SOURCE, PY_COMPILED, or C_EXTENSION, described below.

Thus, to filter this into a list of suffixes for C extension modules:

import imp
extension_suffixes = [suffix for (suffix, mode, type) in imp.get_suffixes()
                             if type == imp.C_EXTENSION]

This also works in Python 3, although imp is deprecated in Python 3.

like image 121
user2357112 supports Monica Avatar answered Dec 09 '25 21:12

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!