Shell指令
执行 Shell 命令,需要 Root 或 Shizuku 权限。
函数定义
system.shell(command: str, callback: ShellListener = None) -> ShellResult
- 参数
| 参数 | 类型 | 是否必填 | 说明 |
|---|---|---|---|
| command | str | 是 | 要执行的 Shell 命令 |
| callback | ShellListener | 否 | 传入则为异步模式,逐行回调输出 |
- 返回值(同步模式)
ShellResult 对象,包含以下属性:
| 属性 | 类型 | 说明 |
|---|---|---|
| res | list | 标准输出,每行一个元素 |
| error | list | 错误输出,每行一个元素 |
| code | int | 退出码,0 表示成功 |
同步模式
from ascript.android import system
# 基础用法 - 获取当前用户
res = system.shell('whoami')
print(res.res) # ['root']
print(res.code) # 0
# 读取系统文件
res = system.shell('cat /system/build.prop | head -5')
print(res.res)
# ['', '# begin build properties', '# autogenerated by buildinfo.sh', ...]
# 列出已安装应用
res = system.shell('pm list packages -3')
for line in res.res:
print(line)
# 获取屏幕分辨率
res = system.shell('wm size')
print(res.res) # ['Physical size: 1080x2400']
# 重置屏幕分辨率
res = system.shell('wm size reset')
print(res.code) # 0
# 模拟按键 (返回键)
system.shell('input keyevent 4')
# 模拟点击坐标
system.shell('input tap 500 1000')
# 模拟滑动
system.shell('input swipe 500 1500 500 500 300')
# 截图保存到指定路径
system.shell('screencap -p /sdcard/screen.png')
# 错误处理
res = system.shell('ls /not_exist')
if res.code != 0:
print('执行失败:', res.error)
异步模式
适用于长时间运行的命令,需要实时获取输出的场景。
- ShellListener
class ShellListener(ABC):
@abstractmethod
def commandOutput(self, i: int, s: str):
# i=0 标准输出, i=1 错误输出
pass
@abstractmethod
def commandTerminated(self, i: int, s: str):
# 当命令被中断时
pass
def commandCompleted(self, i: int, i1: int):
# 当命令执行完毕时
pass
- 示例
from ascript.android import system
from ascript.android.system import ShellListener
class MyListener(ShellListener):
def commandOutput(self, i: int, s: str):
# i=0 标准输出, i=1 错误输出
print('输出:', s)
def commandTerminated(self, i: int, s: str):
print('异常:', s)
def commandCompleted(self, i: int, i1: int):
print('完成, exitCode:', i1)
# 实时监听 logcat
system.shell('logcat -d -s ActivityManager', MyListener())
# 实时监听网络连接
system.shell('netstat -tlnp', MyListener())