【问题标题】:How to reference the current package for use with importlib.resources?如何引用当前包以与 importlib.resources 一起使用?
【发布时间】:2019-11-15 19:23:24
【问题描述】:

我有一个安装包(通常位于…/lib/pythonX.Y/site-packages/my-package 内),其中包含(除其他外)资源…/my-package/a.txt 和…/my-package/b.png。我想使用以下代码从…/my-package/get_my_resources.py 访问这些资源:

txt = importlib.resources.read_text(this_package, 'a.txt')
img = importlib.resources.read_binary(this_package, 'b.png')

this_package 应该使用什么?当我尝试相对自引用this_package = '.' 时,我得到了错误

TypeError: the 'package' argument is required to perform a relative import for '.'

【问题讨论】:

    标签: python python-importlib


    【解决方案1】:

    令人尴尬的简单答案是:

    this_package = __package__
    

    即,

    txt = importlib.resources.read_text(__package__, 'a.txt')
    img = importlib.resources.read_binary(__package__, 'b.png')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多