6.在 Android 上使用 Python¶
Python on Android is unlike Python on desktop platforms. On a desktop platform,Python is generally installed as a system resource that can be used by any userof that computer. Users then interact with Python by running apythonexecutable and entering commands at an interactive prompt, or by running aPython script.
On Android, there is no concept of installing as a system resource. The only unitof software distribution is an "app". There is also no console where you couldrun apython executable, or interact with a Python REPL.
As a result, the only way you can use Python on Android is in embedded mode – thatis, by writing a native Android application, embedding a Python interpreterusinglibpython
, and invoking Python code using thePython embeddingAPI. The full Python interpreter, the standard library, and allyour Python code is then packaged into your app for its own private use.
The Python standard library has some notable omissions and restrictions onAndroid. See theAPI availability guide fordetails.
6.1.將 Python 加入 Android 應用程式¶
Most app developers should use one of the following tools, which will provide amuch easier experience:
If you're sure you want to do all of this manually, read on. You can use thetestbed app as a guide; each step below contains alink to the relevant file.
Build Python by following the instructions inAndroid/README.md.This will create the directory
cross-build/HOST/prefix
.Add code to yourbuild.gradlefile to copy the following items into your project. All except your own Pythoncode can be copied from
prefix/lib
:In your JNI libraries:
libpython*.*.so
lib*_python.so
(外部函式庫,例如 OpenSSL)
In your assets:
python*.*
(Python 標準函式庫)python*.*/site-packages
(你自己的 Python 程式碼)
Add code to your app toextract the assets to the filesystem.
Add code to your app tostart Python in embedded mode. This will need to be C codecalled via JNI.