资源在本地可用,但使用 Poetry 打包和部署时 "No such file or directory"
Resources available locally but "No such file or directory" when packaged and deployed with Poetry
我使用定义为常量的路径,例如TF_CONSTS = 'consts/tf_keras_param_config.json'
并且它们在开发过程中运行良好。
但是,当使用 Poetry(即 poetry build --format sdist
)构建并部署包时,即使 JSON 文件与 Python 脚本一起复制,这些引用也会变得无效:
FileNotFoundError: [Errno 2] No such file or directory: 'some_package/consts/tf_keras_param_config.json'
为什么?
相对路径在开发期间工作正常,但是 - 当代码被打包然后安装时 - 它们必须转换为绝对路径并且必须动态确定(它们取决于安装包的位置):
import pkg_resources
# necessary for the path to resolve properly when package is installed
TF_CONSTS = pkg_resources.resource_filename("some_package", "consts/tf_keras_param_config.json")
也考虑 importlib.resources:
This module provides functionality similar to pkg_resources
Basic Resource Access without the performance overhead of that package. This makes reading resources included in packages easier, with more stable and consistent semantics.
我使用定义为常量的路径,例如TF_CONSTS = 'consts/tf_keras_param_config.json'
并且它们在开发过程中运行良好。
但是,当使用 Poetry(即 poetry build --format sdist
)构建并部署包时,即使 JSON 文件与 Python 脚本一起复制,这些引用也会变得无效:
FileNotFoundError: [Errno 2] No such file or directory: 'some_package/consts/tf_keras_param_config.json'
为什么?
相对路径在开发期间工作正常,但是 - 当代码被打包然后安装时 - 它们必须转换为绝对路径并且必须动态确定(它们取决于安装包的位置):
import pkg_resources
# necessary for the path to resolve properly when package is installed
TF_CONSTS = pkg_resources.resource_filename("some_package", "consts/tf_keras_param_config.json")
也考虑 importlib.resources:
This module provides functionality similar to
pkg_resources
Basic Resource Access without the performance overhead of that package. This makes reading resources included in packages easier, with more stable and consistent semantics.