Categories
Coding Kivy Planet Python PyMT

Introducing “Python for Android”

I’m glad to share a new project called Python for Android. The goal of this project is to package your python application into an APK.

https://github.com/kivy/python-for-android

The project is under the umbrella of Kivy organization, but is not designed to be limited to Kivy only. Read the documentation to correctly install the NDK/SDK Android, and set the needed environment variables.

The packaging is done in 4 steps:
1. Ensure you have Android SDK/NDK downloaded and correctly installed
2. Ensure you have some environment set
3. Create a Python distribution containing the selected modules
4. Use that distribution to build an APK of your Python application

Creating the python distribution is as simple as that:

# create a simple distribution with python + PIL + Kivy
./distribute.sh -m "pil kivy"

# create a distribution with python + openssl + pil + kivy
./distribute.sh -m "openssl pil kivy"

A directory dist/default will be created, including the result of the whole arm compilation.
Available libraries as for today: jpeg pil png sdl sqlite3 pygame kivy android libxml2 libxslt lxml ffmpeg openssl.

The second step is a little bit harder, since you need to provide more information for Android:

cd dist/default
./build.py --package org.test.touchtracer --name touchtracer \
--version 1.0 --dir ~/code/kivy/examples/demo/touchtracer debug installd

# --package: java name of your application
# --name: title of your application
# --version: version of your application
# --dir: location of your application containing the main.py

Then you’ll get a nicely bin/touchtracer-1.0-debug.apk

Pro:

  • A blacklist.txt file that can be used to exclude files in the final APK
  • Reusable distribution for other applications
  • Modular recipes architecture
  • Be able to build independents python distributions

Cons:

  • You need a main.py file that will be used for starting your application
  • Only one java bootstrap available, using OpenGL ES 2.0.
  • Only Kivy toolkit is working. I’m sure that other people can enhance it to add other toolkit recipes. But for example, pygame is not gonna to work because the android project is OpenGL ES 2.0: pygame drawing will not work.

I hope you’ll like it 🙂

We would like to thank Renpy / PGS4A for its initial pygame for android project

41 replies on “Introducing “Python for Android””

Can this be used to package Python programs that rely specifically on C libraries? I have something that uses libusb and there’s a libusb-android port that I could compile pyusb against.

I know nothing about Android development but I know a little about Python development, so… does this mean that I can code a hello.py app with a single line of code “print ‘hello world'”, build it as APK, install it on my android, and it’ll show “Hello World”?!

Can this be used to package Python programs that rely specifically on C libraries? I have something that uses libusb and there’s a libusb-android port that I could compile pyusb against.

Yes/no. You might not have the right / possibility to have a direct access of usb (except if you’re root.). But in theory, you would need to write a recipe for libusb-android, pyusb (with a deps on libusb-android), and then: ./distribute.sh “pyusb” => you’ll have python + pyusb + libusb compiled for ARM.

I know nothing about Android development but I know a little about Python development, so… does this mean that I can code a hello.py app with a single line of code “print ‘hello world’”, build it as APK, install it on my android, and it’ll show “Hello World”?!

No. It will show “Hello World” in the android log (adb logcat), nothing on the screen. This project doesn’t ship any terminal or emulator. If you want to draw something on the screen, you can use the Kivy toolkit (take the hello world from the frontpage kivy.org), then ./distribute.sh -m “kivy”, and package your app, you’ll see the hello world button.

Looks awesome. How hard would it be to combine with Pyside for android, described on http://thp.io/2011/pyside-android/?

I think it’s just a matter of writing a recipe for it (and all the deps not in the project yet) + create a java bootstrap for it (maybe not, dunno about this project.)

[…] Представлен проект Python for android, в рамках которого подготовлен инструментарий, позволяющий создавать приложения для платформы Android на языке Python. Итоговые приложения оформляются в виде APK-пакетов, которые можно установить как обычные приложения для Android. Для обеспечения выполнения интерпретатора Python используется android NDK (Native Development Kit), позволяющий организовать выполнение нативного Си/Си++ кода с задействованием API платформы Android. Код проекта распространяется в рамках лицензии LGPLv2.1. Для формирования пользовательского интерфейса в Python программах для платформы Android предлагается использовать Python-библиотеку Kivy, предназначенную для быстрого создания многоплатформенных GUI-интерфейсов, которые кроме Android также смогт работать в Linux, Windows и Mac OS X. Для формирования интерфейса напрямую используется OpenGL ES 2. Возможно использование различных протоколов ввода, таких как WM_Touch, WM_Pen, Mac OS X Trackpad, Magic Mouse, Mtdev, HID (ядро Linux), TUIO. Поддерживается мультитач, в том числе возможна эмуляция мультитач через использование двух мышей. […]

[…] Представлен проект Python for Android, в рамках которого подготовлен инструментарий, позволяющий создавать приложения для платформы Android на языке Python. Итоговые приложения оформляются в виде APK-пакетов, которые можно установить как обычные приложения для Android. Для обеспечения выполнения интерпретатора Python используется Android NDK (Native Development Kit), позволяющий организовать выполнение нативного Си/Си++ кода с задействованием API платформы Android. Код проекта распространяется в рамках лицензии LGPLv2.1. […]

[…] Представлен проект Python for Android, в рамках которого подготовлен инструментарий, позволяющий создавать приложения для платформы Android на языке Python. Итоговые приложения оформляются в виде APK-пакетов, которые можно установить как обычные приложения для Android. Для обеспечения выполнения интерпретатора Python используется Android NDK (Native Development Kit), позволяющий организовать выполнение нативного Си/Си++ кода с задействованием API платформы Android. Код проекта распространяется в рамках лицензии LGPLv2.1. […]

Is there a tutorial out there that shows a “Hello World”, start to finish, including compilation as an APK and testing on both an Android device and an emulator?

I’d love to do some development on Android, but I have no desire at all to learn Java’s syntax.

How does this approach compare with Py4A (Python for Android http://code.google.com/p/python-for-android/) via SL4A (Scripting Layer for Android http://code.google.com/p/android-scripting/)?

I have managed to cross-compile shared libraries and load them up via ctypes without being root going down this path. The tricky part is the cross-compilation. I am most intrigued that someone has compiled PIL for android. I have had some relatively but hasty yet futile attempts.

Seems something different from Py4a, but is is really awesome. With py4a, we could use use browser as GUI by android.webview().

In the latest IPython (1.2), it supports “notebook()”, a html interface to python programming. This is what I try for making android app. With this “Python for Android”, I had compiled the required dependencies of IPython, uuid, zeromq, pyzmq, tornado; but failed in compiling IPython. Before successfully compiling Ipython, this is one question: is it possible to write a simple python staff to startup notebook(), waiting for services via browser?

Thanks in advanced,

import android
app = android.Android()

app.view(“file:///storage/sdcardo/DCIM/Facebook/IMG_1180747574817.jpeg”,”image/*”)

jpg=PIL.Image.open(‘/storage/sdcard0/DCIM/Facebook/IMG_1180747574817.jpeg’)
pixels = jpg.load()
r,g,b = pixels[x, y]

I try to run this python script on my android device
but this error appeared
PIL is not defined
I try to use your code but I can’t ,can tell me how to defined PIL

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.