Saturday, 3 January 2015

Installing python on Android 5.0

Executables with PIE (Position Independent Execution) have been supported since Android 4.1. It is a security feature involving address space layout randomization(ASLR) to prevent attacks such as buffer overflow. In Android's latest release Lollipop, PIE has been made a requirement. Similar to the way the shift from Dalvik to ART has crippled so many applications, this move has caused a lot of problems to developers.  Even some of the binaries shipped with android itself were broken because of this.

I will be showing you how to install RunPythonFromShell. If you have already installed it and want to see how to bypass PIE go to the section Bypassing PIE.

Step 1

Download apk

Install the apk and open it. Click the install button in the app to install all the modules and binaries.

Step 2 

If you don't want to run python from everywhere, skip this step. 
  • Open adb shell
  • Download the following gist. Move it to /system/bin and change set executable permission.
  • If you are running an android version older than lollipop then you are done! Lollipop users have to bypass PIE.

Bypassing PIE

Due to the PIE restrictions you get the following error when you run python:
         error: only position independent executables (PIE) are supported.

 The idea here is to replace the default linker with a custom linker (You need a rooted device. duh!).  First mount /system in write mode and backup the default linker.

mount -o remount,rw /system /system
mv /system/bin/linker /system/bin/linker.old

Download custom linker

Move custom linker to /system/bin. Then set proper permissions.

chmod 0755 /system/bin/linker

You can also use ES File Explorer or Root Explorer to do this. Permission of the file should look like this:

You are done! You can run python from terminal!

I will be writing a post on what all cool things you can do with python on android. Stay tuned! 


Some of the users with 64 bit architecture were facing some linking problem. Here is what you have to do.
Create a new lib64 directory and move the library file to that folder.

mkdir /data/data/com.googlecode.pythonforandroid/files/python/lib64
cp /usr/lib64/   /data/data/com.googlecode.pythonforandroid/files/python/lib64

Then you have to add this to the library path. To do that you have to update the variable LD_LIBRARY_PATH in the "/system/bin/python" script above.

Thanks Yan Bellavance for pointing it out!