python+adb

python 复制代码
#!/usr/bin/python env
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
from time import sleep

import logging
logging.basicConfig(level=logging.DEBUG)
class ScreenCapture():

    def get_screen_size(self):
        """获取手机分辨率"""

        action = subprocess.Popen(['adb', 'shell', 'wm', 'size'], stdout=subprocess.PIPE)
        result = action.stdout.read()
        _, size = result.decode().split(':')
        self.width,self.height = size.strip().split('x')
        print(f'获取到手机分辨率为:{self.width},{self.height}')  # 1080,2436

        # return int(width), int(height)
        # print(f"result是{result}")
        # print(result.decode())
        # ss=result.decode().split(':')
        # aaa=ss[1].strip()

        self.x1=int(self.width)/2

        self.x2=int(self.width)/2
        self.y1=int(self.height)/4
        self.y2=int(self.height)/1.5
        print(f"x1是{self.x1},x2是{self.x2},y1是{self.y1},y2是{self.y2}")

    @staticmethod
    def show_menu():

        print("========================================================== ")
        print("||      <1>远程连接设备       <2>向左滑动       <3>向右滑动    ||\n")
        print("||      <4>向上滑动           <5>向下滑动       <6>跑Monkey    ||\n")
        print("||      <7>单场景chrome测试   <8>               <9>          ||\n")
        print(" ========================================================= \n")
        # subprocess.Popen(
        #     ['adb', 'shell', 'input', 'swipe', str(self.x1), str(self.y1), str(self.x1), str(self.y2), '500'],
        #     stdout=subprocess.PIPE)
        # return int(width), int(height)
        # self.ScreenCapture(y1, y2, height)
        # subprocess.Popen(['adb', 'shell', 'input', 'swipe', str(self.x1), str(self.y1), str(self.x1), str(self.y2), '500'],stdout=subprocess.PIPE)

    def up_swipe(self):
        up_num = int(input("向上滑动多少次,用数字替代:"))
        interval_time = int(input("输入间隔的时间:"))
        for i in range(up_num):
            subprocess.Popen(
                ['adb', 'shell', 'input', 'swipe', str(self.x1), str(self.y1), str(self.x1), str(self.y2), '500'],
                stdout=subprocess.PIPE)
            print("第{}次滑动".format(i + 1))
            sleep(interval_time)
        print("滑动结束,退出。。")
        sys.exit()

    def down_swipe(self):
        up_num = int(input("向下滑动多少次,用数字替代:"))
        interval_time=int(input("输入间隔的时间:"))
        for i in range(up_num):
            subprocess.Popen(
                ['adb', '-s',{self.ip_input},'shell', 'input', 'swipe', str(self.x1), str(self.y2), str(self.x1), str(self.y1), '500'],
                stdout=subprocess.PIPE)
            sleep(interval_time)
        print("滑动结束,退出。。")
        sys.exit()

    def left_swipe(self):
        x1=str(int(self.width)*0.8)
        x2=str(int(self.width)*0.2)
        y1=str(int(self.height)*0.5)
        print(x1)
        print("滑动开始前")
        up_num = int(input("向左滑动多少次,用数字替代:"))
        for i in range(up_num):

            subprocess.Popen(
                ['adb', 'shell', 'input', 'swipe', x2, y1, x1, y1, '500'],
                stdout=subprocess.PIPE)
            print("第{}次滑动".format(i+1))
            sleep(3)
        print("滑动结束,退出。。")
        sys.exit()

    def right_swipe(self):
        x1 = str(int(self.width) * 0.8)
        x2 = str(int(self.width) * 0.2)
        y1 = str(int(self.height) * 0.5)
        print(x1)
        print("滑动开始前")
        up_num = int(input("向左滑动多少次,用数字替代:"))
        for i in range(up_num):
            subprocess.Popen(
                ['adb', 'shell', 'input', 'swipe', x1, y1, x2, y1, '300'],
                stdout=subprocess.PIPE)
            print("第{}次滑动".format(i + 1))
            sleep(3)
        print("滑动结束,退出。。")
        sys.exit()

    def get_device_id(self):
        self.adb_devices=os.popen("adb devices").read()
        self.adb_output = self.adb_devices.split("List of devices attached\n", 1)[1]
        lines = self.adb_output.strip().split('\n')
        # 遍历每一行,提取设备号
        self.device_ids = []
        for line in lines:
            # 如果行不是空的,并且包含"device",则提取设备号
            if line and "device" in line:
                device_id, _ = line.split(maxsplit=1)  # maxsplit=1确保只分割一次
                self.device_ids.append(device_id.strip())
                self.device_ids=self.device_ids[0]
        logging.info(f'device_ids号是: {self.device_ids}')
        return self.device_ids

    def adb_connect(self, device_ip):
        adb_command = ['adb', 'connect', f'{device_ip}:5555']
        try:
            subprocess.Popen("adb tcpip 5555", stdout=subprocess.PIPE)
            # subprocess.check_call("adb -s {} tcp ip 5555", stdout=subprocess.PIPE)  #
            output = subprocess.check_output(adb_command, shell=True, stderr=subprocess.STDOUT)
            print(f"Connected to device at {device_ip}:5555")
            print(output.decode())
        except:
            print(f"Failed to connect to device at {device_ip}:5555", "请检查错误")
            sys.exit()

    def get_and_connect_ip(self):
        # 将原本在if num == 1下的代码移到这个方法中adb de
        ip_command = f'adb -s {self.get_device_id()} shell ip route'
        result = subprocess.check_output(ip_command, shell=True, text=True)
        # 提取 IP 地址(这里假设IP地址是route命令输出的最后一行最后一个元素)
        ip_address = result.strip('\n').strip(' ').split(' ')[-1]
        print(f"Detected IP address: {ip_address},远程连接需拔掉USB设备")

        self.ip_input = input("输入你的IP地址(或者按回车使用检测到的IP):")
        if not self.ip_input:
            self.ip_input = ip_address  # 如果用户没有输入,则使用检测到的IP
        self.adb_connect(self.ip_input)

        self.run() # 连接后重新显示菜单

    def chrome_switch(self):
        os.system("adb devices")
        while True:
            os.system(f'adb -s {self.ip_input} shell am start -a android.intent.action.VIEW -d "http://baidu.com"')
            sleep(5)
            for i in range(20):
                subprocess.Popen(
                    ['adb', '-s',self.ip_input,'shell', 'input', 'swipe', str(self.x1), str(self.y2),
                     str(self.x1), str(self.y1), '500'],
                    stdout=subprocess.PIPE)
                sleep(3)
            os.system(f'adb -s {self.ip_input} shell am start -a android.intent.action.VIEW -d "http://163.com"')
            sleep(5)
            for i in range(20):
                subprocess.Popen(
                    ['adb', '-s', self.ip_input, 'shell', 'input', 'swipe', str(self.x1), str(self.y2),
                     str(self.x1),
                     str(self.y1), '500'],
                    stdout=subprocess.PIPE)
                sleep(3)

    #def adb_connect(self, ip_input):
        # 假设此方法用于连接ADB
        #print(f"Connecting to ADB with IP: {ip_input}")
        # ... 省略实际连接ADB的代码

    def run(self):
        ScreenCapture.show_menu()  # 假设ScreenCapture是另一个模块或类,并且有show_menu方法
        num = int(input("输入你要选择的功能,用数字替代:"))

        # 定义动作字典
        action_mapping = {
            1: self.get_and_connect_ip,
            2: self.left_swipe,
            3: self.right_swipe,
            4: self.up_swipe,
            5: self.down_swipe,
            7: self.chrome_switch,
        }

        # 检查输入是否在映射中
        if num in action_mapping:
            action_mapping[num]()
        elif num == 6:
            # 对于特定的num值,可以直接处理
            pass
        else:
            print("\n\t输入有误!!!\t\n")
            self.run()  # 递归调用,重新显示菜单和接收输入


if __name__ == '__main__':
    ScreenCapture().run()
相关推荐
shinelord明9 分钟前
【再谈设计模式】享元模式~对象共享的优化妙手
开发语言·数据结构·算法·设计模式·软件工程
游客52014 分钟前
opencv中的各种滤波器简介
图像处理·人工智能·python·opencv·计算机视觉
Monly2116 分钟前
Java(若依):修改Tomcat的版本
java·开发语言·tomcat
boligongzhu16 分钟前
DALSA工业相机SDK二次开发(图像采集及保存)C#版
开发语言·c#·dalsa
Eric.Lee202117 分钟前
moviepy将图片序列制作成视频并加载字幕 - python 实现
开发语言·python·音视频·moviepy·字幕视频合成·图像制作为视频
7yewh19 分钟前
嵌入式Linux QT+OpenCV基于人脸识别的考勤系统 项目
linux·开发语言·arm开发·驱动开发·qt·opencv·嵌入式linux
Dontla21 分钟前
vscode怎么设置anaconda python解释器(anaconda解释器、vscode解释器)
ide·vscode·python
waicsdn_haha31 分钟前
Java/JDK下载、安装及环境配置超详细教程【Windows10、macOS和Linux图文详解】
java·运维·服务器·开发语言·windows·后端·jdk
_WndProc33 分钟前
C++ 日志输出
开发语言·c++·算法
qq_4335545442 分钟前
C++ 面向对象编程:+号运算符重载,左移运算符重载
开发语言·c++