这里有两件不同的事情你可能正在尝试完成:
- 将数据文件视为包的一部分,就像Python模块一样,并在运行时访问它们,即使它并不是普通目录树也可以。
- 在pip安装时将数据文件安装到其他位置,以便您可以正常访问。
这两种方法都在PyPA/setuptools文档的数据文件章节中有解释。我认为你想要第一种方法,在运行时访问数据文件的子部分中有介绍:
通常,现有程序会操作包的
__file__
属性以查找数据文件的位置。然而,这种操作与基于PEP 302的导入钩子(包括从zip文件和Python Eggs中导入)不兼容。强烈建议,如果您正在使用数据文件,则应使用
pkg_resources
的
ResourceManager API来访问它们。
pkg_resources
模块作为
setuptools
的一部分分发,因此,如果您正在使用
setuptools
来分发您的软件包,没有理由不使用其资源管理API。另请参见
访问软件包资源,了解将使用
__file__
的代码转换为使用
pkg_resources
的快速示例。
Follow that link, and you will find what appears to be outdated PEAK documentation. However, this is because they are indeed outdated. There is a
version buried inside the setuptools
docs that may be easier to read and navigate once you locate it.
As stated, you could attempt to use
get_data
(which will function within an egg/zip) and then fallback to accessing a file (which will function when running from source), but it is recommended to use the wrappers in
pkg_resources
. Essentially, if your code was previously doing this:
path = os.path.join(__file__, 'Wordproject/WordProject/Repository/DataBank/', datathingy)
with open(path) as f:
for line in f:
do_stuff(line)
"...你将把它更改为这个:
"
path = 'Wordproject/WordProject/Repository/DataBank/' + datathingy
f = pkg_resources.resource_stream(__name__, path)
for line in f:
do_stuff(line.decode())
注意,
resource_stream
文件始终以二进制模式打开。因此,如果您想将它们作为文本读取,则需要在其周围包装一个
TextIOWrapper
,或对每行进行解码。
pip install
时可以访问的某个位置,还是将它们嵌入到包目录中,并以与访问子模块相同的方式访问它们? - abarnertPyPI
,因为这是一个组织问题。但我更感兴趣的是对代码进行混淆
,以便即使有访问权限,也没有人能够解编包。因此,我希望文件被嵌入到包内部。 - iam.Carrot