How to detect Android OS from a Python script?

Question:

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 sys
>>> 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.

Asked By: ccpizza

||

Answers:

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

Here is a simple check for Android:

import subprocess
subprocess.check_output(['uname', '-o']).strip() == b'Android'
Answered By: Ozgur Bagci

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

import sys
is_android: bool = hasattr(sys, 'getandroidapilevel')

Here are it’s pros and cons:

@@Pros@@
 + Does not depend on environment values
 + Does not depend on third-party modules
 + Simple one-liner (2 technically)

@@Cons@@
 - Version restriction (Supports CPython 3.7+ or equivalent)
 - Implementation-dependent (while CPython implements this I don't know about others)
Answered By: UltraStudioLTD
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.