6. Android で Python を使う

Android における Pythonは、デスクトッププラットフォームにおける Python とは異なります。 デスクトッププラットフォームでは、 Python は一般的にコンピューターのどのユーザーでも使えるシステムリソースとしてインストールされます。そして、ユーザーは python 実行可能ファイルを実行して対話型プロンプトにコマンドを入力したり、 Python スクリプトを実行したりして、 Python を使用することができるのです。

Android においては、システムリソースとしてのインストールという概念はありません。ソフトウェア配布が可能なのは、 "アプリ" だけです。また、 python 実行可能ファイルの実行したり、 Python の REPL を使用したりする、コンソールも存在しません。

このため、 Python を Android 上で使うただ一つの方法は、埋め込みモード、つまり、ネイティブ Android アプリケーションを書き、 libpython を使用して Python インタープリタを埋め込み、そして Python 埋め込み API を使用して Python コードを呼び出すことです。 それにより、完全な Python インタープリタ、標準ライブラリ、及び Python のコードが、アプリにパッケージ化され、独自の私的用途に使用されます。

Python の 標準ライブラリには、 Android におけるいくつかの重要な省略や制限があります。詳細は API 利用可能性ガイド を参照してください。

6.1. Android アプリに Python を追加する

ほとんどのアプリ開発者は、次のツールの一つを使用するべきです。これにより、はるかに簡単な体験が提供されます:

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.

  • First, acquire a build of Python for Android:

    • The easiest way is to download an Android release from python.org. The prefix directory mentioned below is at the top level of the package.

    • Or if you want to build it yourself, follow the instructions in 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:

    • In your JNI libraries:

      • libpython*.*.so

      • lib*_python.so (external libraries such as OpenSSL)

    • In your assets:

      • python*.* (the Python standard library)

      • python*.*/site-packages (your own Python code)

  • 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 packages can be built for Android as wheels and released on PyPI. The recommended tool for doing this is cibuildwheel, which automates all the details of setting up a cross-compilation environment, building the wheel, and testing it on an emulator.