Skip to content

Run Python Scripts in the Android Front-end with Chaquopy

The title may already spark some fires, and before you say it, let me acknowledge it before you. I know Python isn’t the best for writing front-end code in most scenarios. Don’t get me wrong, Python is an amazing language on the back-end which allows you to do powerful things like build programs quickly and leverage machine learning capabilities but on the front-end, there isn’t often reason to Python over, say, Kotlin.

While you definitely can use Python in part or even completely to write Android apps, the question is why would you? Just because it’s there doesn’t mean you must absolutely use it above all else.

Android devices don’t come built in with a Python interpreter, so Python code would have to be interpreted by a pre-packaged Python interpreter, compiled into byte code, then transpiled into Java-compatible bytecode so it can run on the JVM. The result could mean hits on your app’s performance and APK size.

Normally, the better solution would be to let Python run in the back-end and fetch it in the front-end as an API.

Phew, now that that’s out of the way, here’s a few reasons you might actually want to run Python code on the front-end:

  1. There is a huge community of libraries to pull from and perhaps you want to use one or two of them
  2. You have Python scripts of your own which you want to integrate into your app
  3. You absolutely love Python and don’t care about memory or APK size hits
  4. You have all of these reasons considered with the fact that you don’t want to run Python on a back-end server because either you just want to make a small app leveraging Python scripts or you’re doing some testing between Python scripts that you’ll eventually integrate into your back-end server.

In my case, I was testing out Rasa Chatbot as a possible feature but reaching out to people in my back-end team would be more timely and costly than just testing it locally on the client.

Introducing Chaquopy

When it comes to Python for mobile development, the first thing that comes into people’s minds when they’re already familiar with the topic is Kivy which is great if you want to build the entire app in Python.

Now correct me if I’m wrong, but what Kivy doesn’t have is the ability to run as part of an app, alongside Java/Kotlin code. And before you say it, similar libraries like BeeWare are, well, similar.

Chaquopy on the other hand is capable of exactly this. I didn’t want to have to rebuild my whole application in Python just to test one Python script. I just wanted to invoke a function that makes use of a Python script to return a value. Simple. Chaquopy is the only library I found that can do this elegantly. On top of that, it’s super quick to install and easy to use.

Installing Chaquopy into your App

Chaquopy can be installed via Gradle.

First, in your root-level build.gradle file, add these lines.

repositories {
    maven { url "https://chaquo.com/maven" }
}
dependencies {
    classpath 'com.chaquo.python:gradle:6.3.0'
}

Then in your app-level build.gradle file, add these.

apply plugin: 'com.chaquo.python'

defaultConfig {

    sourceSets {
        main {
            python {
                srcDirs = ["src/main/python"]
            }
        }
    }

    python {
        buildPython "/usr/local/bin/python3"
        buildPython "python3"
    }

    ndk {
        abiFilters "armeabi-v7a", "x86"
    }
}

A few notes here, the apply plugin line has to be below apply plugin: ‘com.android.application’ , and your buildPython lines have to refer to the location of Python on your machine. The abiFilters is just enabling ABI for both your devices and emulators, and srcDirs is pointing to a Python folder in your app which you will make.

As it’s been said, make a folder named “python” under src/main. Put any Python scripts here.

Running your Python Scripts

So we’ve got Chaquopy installed, our scripts are in the app, now let’s run them within our app’s code.

if (!Python.isStarted()) {
    Python.start(AndroidPlatform(this))
}

Use this method either in your Activity or Application class to get Python running in your app, ready to execute your scripts. if your app will be using Python consistently across multiple activities, it will be better to start Python in your Application. Otherwise, start it in the activity that needs it.

Here I have an extremely bare Python script called helloworldscript.py

def helloworld():
    return "Hello world Chaquopy!"

By no means am I a full-fledged Python programmer, but this function looks slim and sexy.

Finally, we invoke the Python function from within our code and get a return value as a PyObject.

val python = Python.getInstance()
val pythonFile = python.getModule("helloworldscript")
val helloWorldString = pythonFile.callAttr("helloworld")

hello_textview.text = helloWorldString.toString()

The PyObject can be cast into pretty much any type. There you have it folks, Python running in front-end Android!

Like I said, Python’s true power is truly leveraged when it runs in the back-end, but for use cases like testing features, scripts and such, it does have a few uses in the front-end. I wouldn’t advise you to use it in commercial-level production code though, but hey. I would be really intrigued if someone could prove otherwise! Happy coding ༼ つ ◕_◕ ༽つ

2021 Update: Source Code

Since I wrote this article over a year ago, some of you have been asking for the source code. For the simple bare bones implementation of Chaquopy, check out:

https://github.com/ericdecanini/HelloChaquopy

Or if you want a more production-level implementation of Chaquopy, check out:

https://github.com/ericdecanini/ShopshopShoppingList