Scripting Android with QPython3
Tags: python, qpython3
Published: 2018-05-26 15:07:18

---
title: Scripting Android with QPython3
published: true
description: 
tags: python, QPython3
---

This is my (fledgling and abandoned, due to general lack of efficiency) mobile-only script development workflow [(full post here)](http://blog.matthewodle.com/roll-your-own-name-generator-with-qpython3-on-an-android-device/).

<img src="http://blog.matthewodle.com/wp-content/uploads/2018/02/generated-names-300x97.png" alt="" width="300" height="97" class="alignnone size-medium wp-image-439" />

---

# Dev On the Go

Last summer, I went on a road trip, and wanted to experiment with a mobile-only workflow. The main components I needed were an interpreter, an IDE, and source control.

#### The suite of apps I discovered and used are as follows:
* QPython3 (a python IDE and script runner)
* SGit (source control)
* LabCoat (GitLab repository viewer)
* Dropbox (ad-hoc, easy-access file storage)
* Dropsync (one- or two-way sync between directories on your mobile device)
* Epsilon Notes (a markdown editor and renderer)

In this tutorial, I will cover my experience with QPython3.

---

## Takeaways from this endeavor:

#### Plus:
* It's all in your pocket
* Short feedback loop for testing code

#### Delta:
* Difficult to view information across multiple apps
* Editing code can be a chore
* Not enough charging stations with comfortable seating in that one mall I went to

#### Recommendations:
* Get a bluetooth keyboard
* Bring the portable charger
* Sit uncomfortably close to strangers so you can share the charging station and maybe they'll leave (they didn't leave, but offered to rearrange the seating so we could chum comfortably whilst staring silently at our phones)

## Covered in this post:
1. How to run a 'Hello World!' script in QPython3
1. How to load files into a QPython3 script
1. How I come up with names for my pets

### Install list
* [QPython3 (v1.0.3)](https://play.google.com/store/apps/details?id=org.qpython.qpy3)

## Run Qpython3 and Open hello_world.py
![QPython3 Home](http://blog.matthewodle.com/wp-content/uploads/2018/02/1-qpython-main.png "QPython3 Home")

Select `Programs` > `hello_world.py` > `Open` to view the script contents.

![QPython3 Open](http://blog.matthewodle.com/wp-content/uploads/2018/02/3-qpython-open.png "QPython3 Open")

![QPython3 Hello World Contents](http://blog.matthewodle.com/wp-content/uploads/2018/02/4-qpython-hello-world-contents.png "QPython3 Hello World Contents")

Super standard python3 here. The script uses the [SL4A library](http://pythoncentral.io/python-for-android-the-scripting-layer-sl4a/) (Scripting Layer for Android) to show an Android toast, then prints `Hello world!` to the console.

Click the right-arrow on the bottom toolbar of the script editor screen to run the script. You can also back out of the editor, click `hello_world.py` again, and choose `Run`.

![QPython3 Hello World Execution](http://blog.matthewodle.com/wp-content/uploads/2018/02/5-qpython-hello-world-execution.png "QPython3 Hello World Execution")

That's it!

Play around with some of the other default scripts if you like. To see some of the SL4A library functionality in action, run `test.py` to run a series of tests on various sensors and UI elements. It will demo a few things like text to voice, various form input elements, and progress bars.

---

## Demo Qpython3 App - Item Name Generator!

Now that you're able to execute python scripts on your Android device, let's do the only logical next thing: write a short fantasy equipment name generator script.

### Loading the Files

First, we need to load the file contents. I wrote a quick loadfile function, which takes a filename and returns a list of strings contained in the file.

![QPython3 Namegen Assets](http://blog.matthewodle.com/wp-content/uploads/2018/02/10-qpython-assets.png "QPython3 Namegen Assets")

`weapons.txt`
<pre>
bow
axe
mace
sword
spear
flail
etc
</pre>

Each line in the loaded file will be stored as a separate string in the list by splitting on newline, or `\n`.

`fileutils.py`
<pre>
def loadfile(filename):
    root_path = '/storage/emulated/0/qpython/scrdipts3/modules/namegen/assets/'
    file_path = '{}{}'.format(root_path, filename)
    loaded_file = open (file_path, 'r')
    return loaded_file.read().split('\n')
</pre>

![QPython3 fileutils.py](http://blog.matthewodle.com/wp-content/uploads/2018/02/30-qpython-fileutils.png "QPython3 fileutils.py")

That `root_path` is pretty ugly, but QPython3 does not work with relative paths. It can be improved by using the `os` library:

<pre>
import os

def loadfile(filename):
    root_path = os.path.dirname(os.path.abspath(__file__))
    ...
</pre>

This will let you run the script on other devices, such as a Linux VM.

### The Name Generator Script

#### This script will:
* Import the loadfile function from our `fileutils.py` module
* Read the contents from 3 text files into lists: prefixes, weapons, and suffixes
* For each weapon in the weapons list:
  * Print a string which consists of the current weapon name and a random prefix and suffix

__Step 1__: Load the files. Import the loadfile function from our fileutils module.
<pre>
from fileutils import loadfile
</pre>

__Step 2__: Invoke loadfile to create a weapons list, then print it out to verify.
<pre>
from fileutils import loadfile

weapons = loadfile('weapons.txt')
print (weapons)
</pre>

If you run the script, you should see a list with an entry for each weapon printed to the console:
<pre>
['bow', 'axe', ...]
</pre>

__Step 3__: Invoke loadfile for the prefixes and suffixes.
<pre>
from fileutils import loadfile

weapons = loadfile('weapons.txt')
prefixes = loadfile('prefixes.txt')
suffixes = loadfile('suffixes.txt')
</pre>

__Step 4__: Finally, loop through the weapon list, select a random prefix and suffix, and print out the combination. Don't forget to import the `random` module.
<pre>
import random
from fileutils import loadfile

weapons = loadfile('weapons.txt')
prefixes = loadfile('prefixes.txt')
suffixes = loadfile('suffixes.txt')

for weapon in weapons:
    prefix = random.choice(prefixes)
    suffix = random.choice(suffixes)
    print ("{} {} of {}".format(prefix, weapon, suffix))
</pre>

![QPython3 Namegen Code](http://blog.matthewodle.com/wp-content/uploads/2018/02/20-namegen-code.png "QPython3 Namegen Code")

You should see something similar to this in your console:

![QPython3 Generated Names](http://blog.matthewodle.com/wp-content/uploads/2018/02/40-qpython-generated-names.png "QPython3 Generated Names")

# Conclusion

You should now be familiar with writing and executing python modules on your Android device! Add your own prefixes, suffixes, and weapons to roll your equally awesome counterparts to such legendary names as `satisfactory cuisses of pain`, `repressed flail of efficacy`, and `gesticulating bow of obscurity`!


Thanks for reading!