6. 在 Android 上使用 Python

Android 上的 Python 與桌面版的 Python 不同。在桌面版上,Python 通常作為系統資源安裝,供該台電腦上的任何使用者使用。使用者通常透過執行 python 可執行檔並在互動式提示字元中輸入指令,或是直接執行 Python 腳本與 Python 互動。

在 Android 上,沒有將其安裝為系統資源的概念。唯一的軟體單位是 "app"。也沒有可以執行 python 可執行檔的控制台,或與 Python REPL 互動。

因此,在 Android 上使用 Python 的唯一方式就是以嵌入模式運作 - 也就是撰寫一個原生的 Android 應用程式,使用 libpython 嵌入 Python 直譯器,並透過 Python 嵌入式 API 呼叫 Python 程式碼。完整的 Python 直譯器、標準函式庫,以及你所有的 Python 程式碼,都會被打包進你的應用程式,供該應用程式使用。

Python 的標準函式庫在 Android 上有一些明顯的缺漏與限制。詳情請參考 API 可用性指南

6.1. 將 Python 加入 Android 應用程式

大多數的應用程式開發者應該使用下面其中一種工具,這些工具能提供更輕鬆的使用體驗:

If you're sure you want to do all of this manually, read on. You can use the testbed app as a guide; each step below contains a link to the relevant file.

  • 首先,取得一個用於 Android 的 Python 建置:

    • 最簡單的方式是從 python.org 下載 Android 版本。下面提到的 prefix 目錄位於套件的最上層。

    • Or if you want to build it yourself, follow the instructions in Platforms/Android/README.md. The prefix directory will be created under cross-build/HOST.

  • Add code to your build.gradle file to copy the following items into your project. All except your own Python code can be copied from prefix/lib:

    • 在你的 JNI 函式庫:

      • libpython*.*.so

      • lib*_python.so(外部函式庫,例如 OpenSSL)

    • 在你的資產:

      • python*.*(Python 標準函式庫)

      • python*.*/site-packages(你自己的 Python 程式碼)

  • Add code to your app to extract the assets to the filesystem.

  • Add code to your app to start Python in embedded mode. This will need to be C code called via JNI.

6.2. 建置用於 Android 的 Python 套件

Python 套件可以為 Android 建置成 wheels 並發布到 PyPI。建議使用的工具是 cibuildwheel,它會自動設定交叉編譯環境、建置 wheel,以及在模擬器上測試等所有細節。