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