You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Poetry项目如何访问数据资源文件并解决安装后找不到文件问题

问题解决方案

第一步:配置pyproject.toml声明需要打包的非Python资源文件

Poetry默认只会打包模块内的.py文件,你的lexicon.json属于静态资源,需要手动在pyproject.toml的[tool.poetry]配置块下添加include规则:

[tool.poetry]
# 原有配置保持不变,新增下面一行
include = ["poetry_test/data/*.json"]

如果使用Poetry 1.2及以上版本,也可以用更严谨的资源声明方式:

[tool.poetry]
packages = [{ include = "poetry_test" }]

[tool.poetry.resources]
"poetry_test.data" = ["lexicon.json"]

第二步:修改代码中资源文件的路径读取逻辑

你之前写死的相对路径是相对于当前执行命令的工作目录的,所以只有在项目根目录运行时能找到,切换路径后就会失效,同时安装后的包路径是动态的,不能硬编码。我们用Python标准库的importlib.resources来动态读取包内资源,兼容所有运行场景:
修改后的lexi.py代码如下:

#!/usr/bin/env python3
import sys
import json
# 导入标准库的资源读取模块
from importlib.resources import files

# 动态获取包内data目录下的lexicon.json路径
LEXICON_DB = files("poetry_test").joinpath("data/lexicon.json")


def main():
    args = sys.argv
    if len(args) != 2:
        print("Usage: lexi word")
        sys.exit(1)
    
    word = args[1]
    # 直接用动态路径打开文件即可
    lexicon = json.load(open(LEXICON_DB))
    translation = lexicon.get(word)
    if translation:
        print(translation)
    else:
        print(f"There's no word '{word}' in the lexicon")


if __name__ == '__main__':
    main()

如果需要兼容Python 3.7及更早版本,可以用pkg_resources替代:

import pkg_resources
LEXICON_DB = pkg_resources.resource_filename("poetry_test", "data/lexicon.json")

第三步:重新安装包验证效果

修改完配置和代码后,执行下面命令重新安装包:

# 卸载原有版本
pip uninstall -y poetry-test
# 重新安装当前目录的包
pip install .

安装完成后在任意路径执行lexi zoo都可以正常返回结果。


内容的提问来源于stack exchange,提问作者Pavel Soroka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:15:03