如何从模块定位源代码路径

how to locate source code path from module

我在 /Document/pythonpackage 目录

中有一个从源代码构建的 python 包
/Document/pythonpackage/> python setup.py install

这会在 python

site-packages 目录中创建一个文件夹
import pythonpackage
print(pythonpackage.__file__)
>/anaconda3/lib/python3.7/site-packages/pythonpackage-x86_64.egg/pythonpackage/__init__.py

我是 运行 多个环境中的脚本,所以我知道的唯一路径是 pythonpackage.__file__。但是 Document/pythonpackage 有一些不在站点包中的数据,如果您只能访问 python 中的模块,有没有办法自动找到 /Document/pythonpackage 的路径?

不确定,但您可以为您的模块创建一个存储库并使用 pip 来安装它。然后 egg 文件夹将有一个名为 PKG-INFO 的文件,其中将包含 url 到您从中导入模块的存储库。

不鼓励那样工作。通常假设在安装包之后,用户可以删除安装目录(就像大多数自动化包管理器所做的那样)。相反,您要确保 setup.py 将所有数据文件复制到相关位置,然后您的代码将从那里获取它们。

假设您使用的是标准 setuptools,您可以查看 Including Data Files 上的文档,在底部写着:

In summary, the three options allow you to:

include_package_data

Accept all data files and directories matched by MANIFEST.in.

package_data

Specify additional patterns to match files that may or may not be matched by MANIFEST.in or found in source control.

exclude_package_data

Specify patterns for data files and directories that should not be included when a package is installed, even if they would otherwise have been included due to the use of the preceding options.

然后说:

Typically, existing programs manipulate a package’s __file__ attribute in order to find the location of data files. However, this manipulation isn’t compatible with PEP 302-based import hooks, including importing from zip files and Python Eggs. It is strongly recommended that, if you are using data files, you should use the ResourceManager API of pkg_resources to access them