如何从Python脚本中检测Android操作系统?



我在Android设备上的termux环境中运行python脚本,我希望能够检测到操作系统是Android。

传统方法行不通:

>>> 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'

还有哪些其他 ootb 选项可用?

一个明显有用的选项是返回armv8platform.machine()- 这不仅仅是"Linux",但它只是架构,而不是操作系统,它可能会返回误报,例如在树莓派或其他基于手臂的系统上。

我尝试os.uname()但没有成功。所以我可能会建议使用子进程,因为uname -o返回b'Androidn'.

以下是对Android的简单检查:

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

还有更简单的方法,不依赖于使用外部实用程序,只使用sys模块。 这是代码:

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

以下是它的优缺点:

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

相关内容

最新更新