How to detect Android OS from a Python script?

1.7k Views Asked by At

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.

2

There are 2 best solutions below

9
On BEST ANSWER

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)
3
On

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'