How to get the file extension of dynamic libraries for current OS

I have a demand to load all dynamic libraries given in a directory.

ctypes gives me the capability of loading a dynamic library without considering the prefix and suffix of a library file.

However I don’t know if there’s an existing API to load all dynamic libraries in a directory, or just provide me a value to indicate the suffix of a dynamic library.

Any suggestions?

Can I do this in Python without implementing the functionalities myself? I don’t want to do this

if osname == 'nt':
    suffix = '.dll', '.pyd'
elif osname == ...

Hello!

The one I’m aware of is importlib.machinery.all_suffixes(). It’s not exactly what you are looking for, but it returns all of the suffixes Python looks for when importing. e.g. *.py, *.pyc, *.so

1 Like

Perhaps distutils is helpful here:

from distutils import sysconfig
sysconfig.get_config_var('SHLIB_SUFFIX')

I’m not sure how cross-platform it is. Perhaps some experiments on non-Posix platforms would be useful.

On Windows:

    Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license()" for more information.
    >>> import importlib
    >>> importlib.machinery.all_suffixes()
    ['.py', '.pyw', '.pyc', '.cp37-win_amd64.pyd', '.pyd']
    >>> from distutils import sysconfig
    >>> sysconfig.get_config_var('SHLIB_SUFFIX')
    >>> sysconfig.get_config_var('SHLIB_SUFFIX') is None
    True
    >>> import distutils.ccompiler
    >>> distutils.ccompiler.new_compiler().shared_lib_extension
    '.dll'
2 Likes

Thanks, distutils.ccompiler.new_compiler().shared_lib_extension is what I want!