我想使用 Python 3 中的 importlib.machinery.EXTENSION_SUFFIXES,但不幸的是我使用的是 Python 2.7。
EXTENSION_SUFFIXES 计算为 ['.cpython-34m-x86_64-linux-gnu.so', '.cpython-34m.so', '.abi3.so', '.所以'],但这特定于我的机器和可能的 python 版本,所以我不能简单地硬编码列表。
这是 EXTENSION_SUFFIXES 在 Python 3 源代码中构建的地方:https://github.com/python/cpython/blob/3.6/Lib/importlib/_bootstrap_external.py#L1431 .然而,它似乎进入了 C 实现 ( link ),所以我不清楚如何获得此信息。
如何在 Python 2.7 中获取此列表?
请您参考如下方法:
使用imp.get_suffixes()相反:
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.
因此,要将其过滤到 C 扩展模块的后缀列表中:
import imp
extension_suffixes = [suffix for (suffix, mode, type) in imp.get_suffixes()
if type == imp.C_EXTENSION]
这在 Python 3 中也有效,尽管 imp 在 Python 3 中已弃用。
