How to detect Android OS from a Python script?

Viewed 888

I am running a python script in a termux environment on an Android device and I would like to be able to detect that the OS is Android.

The traditional approaches don't work:

>>> import platform
>>> import system
>>> print(platform.system())
'Linux'
>>> print(sys.platform)
'linux'
>>> print(platform.release())
'4.14.117-perf+'
>>> print(platform.platform())
'Linux-4.14.117-perf+-aarch64-with-libc'

What other ootb options are available?

An apparently useful option is platform.machine() which returns armv8 — this is more than just 'Linux' yet it's just the architecture, and not the OS, and it might return a false positive for example on a raspberry pi or other arm-based systems.

2 Answers

I tried os.uname() without success. So I may suggest using subprocess since uname -o returns b'Android\n'.

Here is a simple check for Android:

import subprocess
subprocess.check_output(['uname', '-o']).strip() == b'Android'

There is more simple way that doesn't depend using external utilities and just uses os module. Here is code:

import os # import **os** module, since we need it's *environ* variable

def isAndroid() -> bool: # function for fast usage
    for item in list(os.environ.keys()): # checks every **key** in **os.environ** dict
        if "ANDROID" in item.upper(): # if **key** contains word **ANDROID** then return True and break [Edit: Add `.upper()` so we can detect in lowercase env variables too]
            return True
    return False # returns False if no match happened

Returns True on both Termux and Pydroid 3, but haven't tested on other environments

This method the theoretically has flaw: Since this method uses environmental list provided by os module, if someone changes it or it simply doesn't contain ANDROID word in keys even if it is Android platform, then it will return False

EDIT: Python 3.7+ option/variant

import sys
is_android: bool = hasattr(sys, 'getandroidapilevel') # Availability = 3.7+

This option doesn't have any flaws except Version limit/availability and possible not-implemention in any other implementation.

Related