安卓端性能-python+adb实现流量测试自动化

背景

上一篇介绍了adb采集流量的方案和采集验证过程,这一篇记录一下具体的实现方案:python + adb
上一篇传送门 -> https://www.cnblogs.com/alisleepy/p/18567796

实现技术

1、python
2、adb

具体编码

# 方法1:获取进程PID
# 方法2:根据进程PID获取流量信息,支持获取 手机卡流量、wifi流量

import subprocess
import re
import os

@staticmethod
def get_app_pid(deviceid, package_name="com.XX.XXX") -> int:
    """
    获取deviceid这台机器的pid信息
    :param deviceid: 设备连接id
    :param package_name: 包名
    :return: pid
    :rtype : int
    """
    try:
        cmd_cpu = "adb -s " + deviceid + " shell ps | grep " + package_name
        pid = 0
        cpu_info = subprocess.Popen(cmd_cpu, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        while cpu_info.poll() is None:
            cpu_line = cpu_info.stdout.readline().decode("utf8")
            cpu_split = cpu_line.split()
            if len(cpu_split) >= 1 and cpu_split[-1] == package_name:
                pid = cpu_split[1]
                break
        return int(pid)
    except Exception as e:
        return 0

@staticmethod
def get_flow_by_pid(pid, dataType="traffic") -> int:
    """
    根据进程id获取流量
    :param pid: int, 进程id
    :param dataType: str, 采集的流量类型,默认为traffic,表示手机流量,支持 all、wifi、traffic
    Returns:
    """
    if dataType not in ["all", "wifi", "traffic"]:
        raise ValueError("Invalid dataType value")
    
    command = f'adb shell cat /proc/{pid}/net/dev'
    result = os.popen(command).read().strip().split('\n')[2:]
    total_flow = 0

    for line in result:
        # 本地流量不采集
        if line.split()[0] == "lo:":
            continue
        # 如果采集流量
        if dataType == "traffic":
            if not re.search("^rmnet_data\d", line.split()[0]):
                continue
            total_flow += int(line.split()[1]) + int(line.split()[9])  # 1和9分别对应接收和发送的数据
        # 如果采集wifi流量
        elif dataType == "wifi":
            if not re.search("^wlan\d", line.split()[0]):
                continue
            total_flow += int(line.split()[1]) + int(line.split()[9])  # 1和9分别对应接收和发送的数据
        else:
            # 采集wifi + 手机卡流量
            if not re.search("^wlan\d", line.split()[0]) and not re.search(
                    "^rmnet_data\d", line.split()[0]
            ):
                continue
            total_flow += int(line.split()[1]) + int(line.split()[9])  # 1和9分别对应接收和发送的数据
    return total_flow


posted @ 2024-11-25 16:00  alisleepy  阅读(1)  评论(0编辑  收藏  举报