在 .pex 中导入 json 资源(Python 可执行文件(Twitter 格式))

Importing json resources inside .pex (Python Executable (format by Twitter))

我在完成构建时使用 Twitter 工程构建工具 pants to manage many projects inside my monorepo. It outputs .pex 文件,这是一个二进制文件,它打包了每个项目所需的最低限度的依赖项,并使它们成为“二进制文件”(实际上一个在 运行 时间解压缩的存档),我的问题是我的代码使用了很长时间的实用程序无法检测到一些我存储的 .json 文件(现在我正在使用裤子)在我的环境库下。我的所有其他代码似乎 运行 都很好。我很确定它与我的配置有关,也许我没有正确存储资源所以我的代码可以找到它,尽管当我使用 unzip my_app.pex 时,我想要的资源在包中并位于正确的位置(目录)。这是我的实用程序用来加载 json 资源的方法:

if test_env:
    file_name = "test_env.json"
elif os.environ["ENVIRONMENT_TYPE"] == "PROD":
    file_name = "prod_env.json"
else:
    file_name = "dev_env.json"
try:
    json_file = importlib.resources.read_text("my_apps.environments", file_name)
except FileNotFoundError:
    logger.error(f"my_apps.environments->{file_name} was not found")
    exit()
config = json.loads(json_file)

这是我目前用于这些资源的 BUILD 文件:

python_library(
   dependencies=[
       ":dev_env",
       ":prod_env",
       ":test_env"
   ]
 )

resources(
   name="dev_env",
   sources=["dev_env.json"]
)

resources(
   name="prod_env",
   sources=["prod_env.json"]
)

resources(
   name="test_env",
   sources=["test_env.json"]
)

这是调用这些资源的实用程序的 BUILD 文件,上面的 python 代码就是您所看到的:

python_library(
   name="environment_handler",
   sources=["environment_handler.py"],
   dependencies=[
       "my_apps/environments:dev_env",
       "my_apps/environments:prod_env",
       "my_apps/environments:test_env"
   ]
)

我总是遇到 FileNotFoundError 异常,我很困惑,因为这些文件在 运行 时间内可用,是什么导致这些文件无法访问?我需要将 JSON 资源设置为其他格式吗?

这里还有解压缩的 .pex 文件(实际上只是源代码目录)的上下文:

    ├── apps
│   ├── __init__.py
│   └── services
│       ├── charts
│       │   ├── crud
│       │   │   ├── __init__.py
│       │   │   └── patch.py
│       │   ├── __init__.py
│       │   └── main.py
│       └── __init__.py
├── environments
│   ├── dev_env.json
│   ├── prod_env.json
│   └── test_env.json
├── __init__.py
├── models
│   ├── charts
│   │   ├── base.py
│   │   └── __init__.py
│   └── __init__.py
└── utils
    ├── api_queries
    │   ├── common
    │   │   ├── connections.py
    │   │   └── __init__.py
    │   └── __init__.py
    ├── calculations
    │   ├── common
    │   │   ├── __init__.py
    │   │   └── merged_user_management.py
    │   └── __init__.py
    ├── environment_handler.py
    ├── __init__.py
    ├── json_response_toolset.py
    └── security_toolset.py

我想通了:我改变了我访问库中文件的方式,它在构建为 .pex 格式之前和之后都能完美运行。我用过:

import pkgutil
#json_file = importlib.resources.read_text("my_apps.environments", file_name)
json_file = pkgutil.get_data("my_apps.environments", file_name).decode("utf-8")