前言
appt
aapt即Android Asset Packaging Tool,在SDK的build-tools目录下。该工具可以查看,创建, 更新ZIP格式的文档附件(zip, jar, apk),也可将资源文件编译成二进制文件。aapt 命令可应用于查看apk包名、主activity、版本等很多信息。
Popen
Popen()可以执行shell命令,并读取此命令的返回值;当我们需要调用系统的命令的时候,最先考虑的os模块。用os.system()和os.popen()来进行操作。但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命令的输出,判断该命令的运行状态,管理多个命令的并行等等。这时subprocess中的Popen命令就能有效的完成我们需要的操作。
Popen它的构造函数如下:
subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
代码
前面我们已经谈过如何获取app应用信息的命令,及使用Python中的subprocess.Popen()方法执行shell命令。下面直接进入正题上代码:
# coding=utf-8
__author__ = "Enoch"
"""
apkInfo app的相关参数信息
"""
from math import floor
import os
import subprocess
class ApkInfo:
# 待测试应用路径
apkPath = "F:\\kaoyan.apk"
def __init__(self):
self.aapt = "D:\\ProgramFiles\\android-sdk-windows\\build-tools\\28.0.3\\aapt dump badging "
# 获取app的文件大小
def get_apk_size(self):
size = floor(os.path.getsize(self.apkPath)/(1024*1000))
return str(size) + "M"
# 获取app的版本信息
def get_apk_version(self):
cmd = self.aapt + self.apkPath
result = ""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
if output != "":
result = output.split()[3].decode()[12:]
result = result.split("'")[1]
return result
# 获取app的名字
def get_apk_name(self):
cmd = self.aapt + self.apkPath + " | findstr application-label-zu: "
result = ""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
output = str(output, encoding='utf8')
if output != "":
result = output.split("'")[1]
return result
# 获取app的包名
def get_apk_package(self):
cmd = self.aapt + self.apkPath + " | findstr package:"
result = ""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
output = str(output, encoding='utf8')
if output != "":
result = output.split()[1][6:-1]
return result
# 得到启动类
def get_apk_activity(self):
cmd = self.aapt + self.apkPath + " | findstr launchable-activity:"
result = ""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
if output != "":
result = output.split()[1].decode()[6:-1]
return result
if __name__ == '__main__':
apkInfo = ApkInfo()
print("应用名称:", apkInfo.get_apk_name())
print("app文件大小:", apkInfo.get_apk_size())
print("app版本信息:", apkInfo.get_apk_version())
print("app包名:", apkInfo.get_apk_package())
print("app的启动类:", apkInfo.get_apk_activity())