如何从modu定位源代码路径

2024-06-16 13:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在/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的路径?你知道吗


Tags: installpyimport路径目录文件夹源代码packages
2条回答

那样工作是不鼓励的。一般认为,在安装包之后,用户可以删除安装目录(大多数自动化包管理器都会这样做)。相反,您应该确保您的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

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

相关问题 更多 >