如何获取安装python包的文件夹路径?

How to get installed python package folder path?

如何安装 python Python C API 中的软件包文件夹路径?

假设我想从 Python C-API module.pyd 打开一个文件 data.txt,它位于如下位置:

package
   |--module.pyd
   |--data
   |    |-data.txt

如何获取 data.txt 的路径名?


该过程类似于纯 Python 的过程,如以下所述:

  • Retrieving python module path

因为您仍然可以在 C 扩展对象上查找 __file__

>>> import wrapt._wrappers
>>> wrapt._wrappers.__file__
'/Users/graham/Python/wrapt-py36/lib/python3.6/site-packages/wrapt/_wrappers.cpython-36m-darwin.so'

在 C 代码中,您只需使用 C API 完成这些步骤。

PyObject *module = NULL;
PyObject *file = NULL;

module = PyImport_ImportModule('package.module');

if (module) {
    PyObject *dict = NULL;

    dict = PyModule_GetDict(module);

    file = PyDict_GetItemString(dict, "__file__");

    if (file) {
        ...
    }

    Py_XDECREF(file);
}

Py_XDECREF(module);

然后您需要删除路径的最后一段以获取目录并构建到另一个文件的路径。我没有显示代码,这取决于是想自己用 C 代码做,还是想尝试从 Python.

调用 os.path 函数

此外,最好将 C 扩展包装在一个薄的 Python 包包装器中。这样一来,这些在 Python 代码中更容易做的事情就可以作为一个函数在那里完成。如果确实需要,您的 C API 代码可以调用您的纯 Python 函数。换句话说,只需将需要在 C 代码中的东西放在扩展中,而在 Python 包装器中做其他工作,可以节省很多工作。