在Python项目中管理资源 [英] Managing resources in a Python project
问题描述
我有一个Python项目,其中正在使用许多非代码文件。当前这些都是图像,但是将来我可能会使用其他类型的文件。
I have a Python project in which I am using many non-code files. Currently these are all images, but I might use other kinds of files in the future. What would be a good scheme for storing and referencing these files?
我考虑过只是在主目录中创建一个文件夹 resources,但这是有问题的。一些图像是从我项目的子包中使用的。以这种方式存储这些图像会导致耦合,这是一个缺点。
I considered just making a folder "resources" in the main directory, but there is a problem; Some images are used from within sub-packages of my project. Storing these images that way would lead to coupling, which is a disadvantage.
此外,我还需要一种访问这些文件的方法,该方法与当前目录无关。
Also, I need a way to access these files which is independent on what my current directory is.
推荐答案
您可能要使用 pkg_resources
随<$附带的库c $ c> setuptools 。
例如,我制作了一个快速的小包装 proj
来说明我将使用的资源组织方案:
For example, I've made up a quick little package "proj"
to illustrate the resource organization scheme I'd use:
proj/setup.py
proj/proj/__init__.py
proj/proj/code.py
proj/proj/resources/__init__.py
proj/proj/resources/images/__init__.py
proj/proj/resources/images/pic1.png
proj/proj/resources/images/pic2.png
注意我如何将所有资源保存在
Notice how I keep all resources in a separate subpackage.
code.py
显示了 pkg_resources
用于引用资源对象:
"code.py"
shows how pkg_resources
is used to refer to the resource objects:
from pkg_resources import resource_string, resource_listdir
# Itemize data files under proj/resources/images:
print resource_listdir('proj.resources.images', '')
# Get the data file bytes:
print resource_string('proj.resources.images', 'pic2.png').encode('base64')
如果运行它,您将得到:
If you run it, you get:
['__init__.py', '__init__.pyc', 'pic1.png', 'pic2.png']
iVBORw0KGgoAAAANSUhE ...
如果您需要将资源视为文件对象,请使用 resource_stream()
。
If you need to treat a resource as a fileobject, use resource_stream()
.
访问资源的代码可能在项目子包结构中的任何位置,只需要引用包含全名图像的子包:在这种情况下,是 proj.resources.images
。
The code accessing the resources may be anywhere within the subpackage structure of your project, it just needs to refer to subpackage containing the images by full name: proj.resources.images
, in this case.
setup.py
:
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='proj',
packages=find_packages(),
package_data={'': ['*.png']})
注意事项:
要本地测试,即首先不安装软件包,必须从具有 setup.py $ c的目录中调用测试脚本。 $ c>。如果您与
code.py
位于同一目录中,Python将不会知道 proj
软件包。因此, proj.resources
之类的东西将无法解决。
Caveat:
To test things "locally", that is w/o installing the package first, you'll have to invoke your test scripts from directory that has setup.py
. If you're in the same directory as code.py
, Python won't know about proj
package. So things like proj.resources
won't resolve.
这篇关于在Python项目中管理资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!