test-adb.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # import uiautomator2 as u2
  2. # d = u2.connect('127.0.0.1:52377') # 例如:"127.0.0.1:61468"
  3. #
  4. # print('>>>>',d.info)
  5. import subprocess
  6. import os
  7. import subprocess
  8. import os
  9. def run_adb_command(command, adb_path=None):
  10. """
  11. 执行 ADB 命令并返回输出,可以通过环境变量指定 ADB 路径。
  12. Args:
  13. command (list): 包含 ADB 命令及其参数的列表。
  14. adb_path (str, optional): ADB 可执行文件的完整路径。
  15. 如果为 None,则使用系统环境变量中的 ADB,
  16. 或者在代码中设置的自定义环境变量。
  17. Returns:
  18. str: 命令的标准输出,如果执行失败则返回 None。
  19. """
  20. env = os.environ.copy() # 复制当前的环境变量
  21. adb_executable = adb_path + "\\adb.exe"
  22. if adb_path:
  23. # 在子进程的环境变量中设置 ADB 的路径
  24. # adb_executable = adb_path
  25. env["PATH"] = os.pathsep.join([os.path.dirname(adb_path), env.get("PATH", "")])
  26. # else:
  27. try:
  28. full_command = [adb_executable] + ["shell"] + command
  29. result = subprocess.run(
  30. full_command,
  31. capture_output=True,
  32. text=True,
  33. check=True,
  34. env=env # 将设置的环境变量传递给子进程
  35. )
  36. return result.stdout.strip()
  37. except subprocess.CalledProcessError as e:
  38. print(f"ADB 命令 '{' '.join(command)}' 执行失败:")
  39. print(f"错误代码: {e.returncode}")
  40. print(f"错误输出:\n{e.stderr}")
  41. return None
  42. except FileNotFoundError:
  43. print(f"错误: ADB 可执行文件 '{adb_executable}' 未找到。请检查路径是否正确。")
  44. return None
  45. def list_devices(adb_path=None):
  46. """
  47. 列出已连接的 Android 设备。
  48. Args:
  49. adb_path (str, optional): ADB 可执行文件的完整路径。 Defaults to None.
  50. """
  51. command = ["devices"]
  52. output = run_adb_command(command, adb_path)
  53. if output:
  54. print("已连接的设备:")
  55. for line in output.splitlines()[1:]:
  56. if line.strip():
  57. device_info = line.split('\t')
  58. print(f"- {device_info[0]}")
  59. else:
  60. print("未找到已连接的 Android 设备。")
  61. def get_screen_size(device_serial=None, adb_path=None):
  62. """
  63. 获取指定设备的屏幕尺寸。
  64. Args:
  65. device_serial (str, optional): 设备的序列号。 Defaults to None.
  66. adb_path (str, optional): ADB 可执行文件的完整路径。 Defaults to None.
  67. """
  68. command_base = []
  69. if device_serial:
  70. command_base.extend(["-s", device_serial])
  71. command_base.extend(["wm", "size"])
  72. output = run_adb_command(command_base, adb_path)
  73. if output:
  74. if "Physical size" in output:
  75. size_str = output.split(":")[1].strip()
  76. print(f"屏幕尺寸: {size_str}")
  77. return size_str
  78. else:
  79. print(f"无法获取屏幕尺寸: {output}")
  80. return None
  81. return None
  82. def tap_screen(x, y, device_serial=None, adb_path=None):
  83. """
  84. 模拟点击屏幕指定坐标。
  85. Args:
  86. x (int): 点击的 X 坐标。
  87. y (int): 点击的 Y 坐标。
  88. device_serial (str, optional): 设备的序列号。 Defaults to None.
  89. adb_path (str, optional): ADB 可执行文件的完整路径。 Defaults to None.
  90. """
  91. command_base = []
  92. if device_serial:
  93. command_base.extend(["-s", device_serial])
  94. command_base.extend(["input", "tap", str(x), str(y)])
  95. print(f"模拟点击坐标 ({x}, {y})")
  96. run_adb_command(command_base, adb_path)
  97. def swipe_screen(start_x, start_y, end_x, end_y, duration_ms=None, adb_path=None):
  98. """
  99. 模拟屏幕滑动操作。
  100. Args:
  101. start_x (int): 滑动起始 X 坐标。
  102. start_y (int): 滑动起始 Y 坐标。
  103. end_x (int): 滑动结束 X 坐标。
  104. end_y (int): 滑动结束 Y 坐标。
  105. duration_ms (int, optional): 滑动持续时间 (毫秒). Defaults to None.
  106. adb_path (str, optional): ADB 可执行文件的完整路径。 Defaults to None.
  107. """
  108. command_base = ["input", "swipe", str(start_x), str(start_y), str(end_x), str(end_y)]
  109. if duration_ms is not None:
  110. command_base.append(str(duration_ms))
  111. run_adb_command(command_base, adb_path)
  112. if __name__ == "__main__":
  113. # 假设你的 ADB 路径是:
  114. # adb_custom_path = "/path/to/your/android-sdk/platform-tools/adb" # 请替换为你的实际路径
  115. adb_custom_path = "../bin/windows/platform-tools" # 请替换为你的实际路径
  116. print("--- 列出已连接的设备 (通过设置环境变量) ---")
  117. list_devices(adb_path=adb_custom_path)
  118. # 尝试获取第一个连接设备的屏幕尺寸 (通过设置环境变量)
  119. print("\n--- 获取屏幕尺寸 (通过设置环境变量) ---")
  120. screen_size_str = get_screen_size(adb_path=adb_custom_path)
  121. screen_width = None
  122. screen_height = None
  123. if screen_size_str:
  124. try:
  125. width, height = map(int, screen_size_str.split("x"))
  126. screen_width = width
  127. screen_height = height
  128. print(f"屏幕宽度: {screen_width}, 屏幕高度: {screen_height}")
  129. except ValueError:
  130. print("无法解析屏幕尺寸字符串。")
  131. # 模拟点击屏幕中间 (如果获取到屏幕尺寸,并设置环境变量)
  132. if screen_width and screen_height:
  133. center_x = screen_width // 2
  134. center_y = screen_height // 2
  135. print("\n--- 模拟点击屏幕中间 (通过设置环境变量) ---")
  136. tap_screen(center_x, center_y, adb_path=adb_custom_path)
  137. swipe_screen(center_x, center_y, center_x, center_y * 1.5, adb_path=adb_custom_path)