在Python模块发行版中查找文件 [英] Finding a file in a Python module distribution

查看:65
本文介绍了在Python模块发行版中查找文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个Python程序包,其中包含一个bsddb数据库,该数据库包含预先计算的值,用于更耗时的计算之一。为简单起见,我的设置脚本将数据库文件安装在与访问数据库的代码相同的目录中(在Unix上,类似于/usr/lib/python2.5/site-packages/mypackage /)。

I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).

如何存储数据库文件的最终位置,以便我的代码可以访问它?现在,我正在使用基于访问数据库的模块中 __ file __ 变量的黑客工具:

How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the __file__ variable in the module which accesses the database:


dbname = os.path.join(os.path.dirname(__file__), "database.dat")

可以,但是似乎...有点黑。有一个更好的方法吗?我想让安装脚本从distutils模块中获取最终安装位置,并将其填充到一个 dbconfig.py文件中,该文件与访问数据库的代码一起安装。

It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.

推荐答案

尝试使用pkg_resources,它是setuptools的一部分(并且在我现在可以访问的所有python上都可用):

Try using pkg_resources, which is part of setuptools (and available on all of the pythons I have access to right now):

>>> import pkg_resources
>>> pkg_resources.resource_filename(__name__, "foo.config")
'foo.config'
>>> pkg_resources.resource_filename('tempfile', "foo.config")
'/usr/lib/python2.4/foo.config'

关于使用pkg_resources在鸡蛋页面和 pkg_resources 页面。

There's more discussion about using pkg_resources to get resources on the eggs page and the pkg_resources page.

还请注意,在可能的情况下,建议使用pkg_resources.resource_stream或pkg_resources.resource_string,因为如果软件包是egg的一部分,则resource_filename会将文件复制到临时目录。

Also note, where possible it's probably advisable to use pkg_resources.resource_stream or pkg_resources.resource_string because if the package is part of an egg, resource_filename will copy the file to a temporary directory.

这篇关于在Python模块发行版中查找文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆