demo_adb.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import subprocess
  2. import os
  3. import time
  4. def take_screenshot(device_ip, device_port, save_path='screenshots'):
  5. # 构建连接命令
  6. connect_command = f'adb connect {device_ip}:{device_port}'
  7. subprocess.run(connect_command, shell=True, check=True)
  8. # 构建设备特定的截图命令
  9. timestamp = time.strftime('%Y%m%d_%H%M%S')
  10. screenshot_name = f'screenshot_{timestamp}.png'
  11. screenshot_path = os.path.join(save_path, screenshot_name)
  12. # 检查保存路径是否存在,如果不存在则创建
  13. if not os.path.exists(save_path):
  14. os.makedirs(save_path)
  15. # 执行截图命令
  16. screenshot_command = f'adb -s {device_ip}:{device_port} shell screencap -p /sdcard/{screenshot_name}'
  17. subprocess.run(screenshot_command, shell=True, check=True)
  18. # 从设备拉取截图到本地指定路径
  19. pull_command = f'adb -s {device_ip}:{device_port} pull /sdcard/{screenshot_name} {screenshot_path}'
  20. subprocess.run(pull_command, shell=True, check=True)
  21. # 删除设备上的截图文件
  22. remove_command = f'adb -s {device_ip}:{device_port} shell rm /sdcard/{screenshot_name}'
  23. subprocess.run(remove_command, shell=True, check=True)
  24. print(f'Screenshot saved as {screenshot_path}')
  25. if __name__ == '__main__':
  26. device_ip = '192.168.1.100' # 替换为你设备的IP地址
  27. device_port = '5555' # 替换为你设备的端口号
  28. take_screenshot(device_ip, device_port)