命令

    1. adb shell dumpsys battery

    image.png

    设置手机非充电状态

    1. adb shell dumpsys battery set status 1

    重置

    1. adb shell dumpsys battery reset

    python代码

    1. import csv
    2. import subprocess
    3. import time
    4. #控制类
    5. class Controller(object):
    6. def __init__(self, count):
    7. #定义测试的次数
    8. self.counter = count
    9. #定义收集数据的数组
    10. self.alldata = [("timestamp", "power")]
    11. #单次测试过程
    12. def testprocess(self):
    13. #执行获取电量的命令
    14. result = subprocess.Popen("adb shell dumpsys battery",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    15. #获取电量的level
    16. for line in result.stdout.readlines():
    17. line = line.decode('utf-8')
    18. if "level" in line:
    19. power = line.split(":")[1]
    20. power = power.strip()
    21. print("power===",power)
    22. break
    23. #获取当前时间
    24. currenttime = self.getCurrentTime()
    25. #将获取到的数据存到数组中
    26. self.alldata.append((currenttime, power))
    27. #多次测试过程控制
    28. def run(self):
    29. #设置手机进入非充电状态
    30. subprocess.Popen("adb shell dumpsys battery set status 1",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    31. while self.counter >0:
    32. self.testprocess()
    33. self.counter = self.counter - 1
    34. #每5秒钟采集一次数据
    35. time.sleep(1)
    36. #获取当前的时间戳
    37. def getCurrentTime(self):
    38. currentTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    39. return currentTime
    40. #数据的存储
    41. def SaveDataToCSV(self):
    42. csvfile = open('battary.csv', 'w',newline='')
    43. writer = csv.writer(csvfile)
    44. writer.writerows(self.alldata)
    45. csvfile.close()
    46. if __name__ == "__main__":
    47. controller = Controller(5)
    48. controller.run()
    49. controller.SaveDataToCSV()