【问题标题】:Python read static file from within a pip package that I've deployedPython 从我部署的 pip 包中读取静态文件
【发布时间】:2021-08-10 15:36:07
【问题描述】:

感谢阅读问题。

我遇到了SO post,其中一个解决方案讨论了使用我正在尝试使用的pkg_resources。

我的文件结构

x
  - x
    - to_read.json
    - __init__.py
  - to_read.json
  - __init__.py 

是的,我复制了它。在 x 文件夹下也是如此

我的设置文件

from setuptools import find_packages, setup

setup(
    name='x',
    version='0.160',
    packages=find_packages(exclude="tests/"),
    url="git@github.com:A/B.git",
    package_data={'x': [
        'to_read.json',
        "x/to_read.json"
    ]},
    install_requires=["foo", "bar"]
)

代码试图读取它

  1. 错误:Exception: the 'package' argument is required to perform a relative import for '.'
return json.loads(str(pkg_resources.open_text(".", 'to_read')))  # note, I removed the extension as mentioned in the solution
  1. FileNotFoundError
return json.loads(str(pkg_resources.open_text("x", 'to_read')))  # note, I removed the extension as mentioned in the solution

我认为我不必导入任何东西(SO 帖子导入的“模板”),因为它位于我目录的顶层?

谢谢!

【问题讨论】:

    标签: python deployment pip setuptools


    【解决方案1】:

    解决办法是

    1. 导入库....import mylib

    with pkg_resources.open_text(mylib, 'to_read.json') as file:
        return json.load(file)
    

    所以基本上我认为不应该应用的所有东西都适用了。翻录

    【讨论】:

      猜你喜欢
      • 2011-08-27
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      相关资源
      最近更新 更多