03.8.1 Python

使用受支持的构建系统(如 Meson、CMake 或 Autotools)的 Python 应用程序可以使用标准方法构建。然而,许多 Python 应用程序使用自定义安装脚本,或者预期通过 Setuptools 和 pip 安装。

对于这些情况,flatpak-builder 提供了 simple 构建系统。它不是自动化构建过程,而是接受一个 build-commands 字符串数组,按顺序执行。

例如,以下 YAML 使构建流行的 requests 模块变得相当直接:

name: requests
buildsystem: simple
build-commands:
  - pip3 install --prefix=/app --no-deps .
sources:
  - type: archive
    url: https://files.pythonhosted.org/packages/b0/e1/eab4fc3752e3d240468a8c0b284607899d2fbfb236a56b7377a329aa8d09/requests-2.18.4.tar.gz
    sha256: 9c443e7324ba5b85070c4a818ade28bfabedf16ea10206da1132edaa6dda237e

这里,build-commands 是一个包含构建和安装模块所需命令的数组。--prefix=/app 选项很重要,因为否则 pip 会尝试在 /usr/ 下安装模块,而由于 /usr/ 在沙箱内是只读挂载的,这会失败。

构建多个 Python 依赖项

对于更复杂的依赖关系,可以使用 flatpak-pip-generator 来生成必要的清单 JSON。

使用 flatpak-pip-generator 非常简单:

$ python3 flatpak-pip-generator requests

或者如果您有 requirements.txt 文件:

$ python3 flatpak-pip-generator --requirements-file=requirements.txt

这将输出一个名为 python3-requests.json 的文件,然后在应用程序的清单文件中引用它:

modules:
  - python3-requests.json