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

ccp*_*zza 6 python android os-detection

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

\n

传统方法不起作用:

\n
>>> import platform\n>>> import sys\n>>> print(platform.system())\n\'Linux\'\n>>> print(sys.platform)\n\'linux\'\n>>> print(platform.release())\n\'4.14.117-perf+\'\n>>> print(platform.platform())\n\'Linux-4.14.117-perf+-aarch64-with-libc\'\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

一个明显有用的选项是platform.machine()返回armv8\xe2\x80\x94 这不仅仅是 \'Linux\' 但它只是架构,而不是操作系统,并且它可能会返回误报,例如在树莓派上或其他基于arm的系统。

\n

USL*_*LTD 1

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

import sys
is_android: bool = hasattr(sys, 'getandroidapilevel')
Run Code Online (Sandbox Code Playgroud)

以下是它的优点和缺点:

@@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)
Run Code Online (Sandbox Code Playgroud)