在安卓设备开发中,有的安卓设备只能通过ADB命令安装,反复的输出ADB命令比较麻烦,我们可以通过Python命令直接选择路径与设备安装非常的方便。
1.安装Python环境,选择一个版本安装就可以
Python官方地址:Welcome to Python.org
2.代码部分
import os
import subprocess
from tkinter import Tk, filedialog
LAST_IP_FILE = "last_ip.txt"
def get_adb_path():
"""返回脚本所在目录的 adb 路径"""
script_dir = os.path.dirname(os.path.abspath(__file__))
adb_path = os.path.join(script_dir, 'platform-tools', 'adb.exe')
print(f"\n脚本所在目录: {script_dir}")
print(f"正在使用 ADB 路径: {adb_path}")
return adb_path
def get_connected_devices(adb_path):
"""获取当前连接的设备列表"""
try:
result = subprocess.run([adb_path, 'devices'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
lines = result.stdout.strip().split('\n')[1:] # 跳过第一行
devices = [line.split('\t')[0] for line in lines if '\tdevice' in line]
return devices
except Exception as e:
print(f"获取设备列表失败: {e}")
return []
def connect_via_wifi(adb_path):
"""连接无线设备,自动记录上次 IP"""
last_ip = ""
if os.path.exists(LAST_IP_FILE):
with open(LAST_IP_FILE, "r") as f:
last_ip = f.read().strip()
if last_ip:
use_last = input(f"是否使用上次的 IP({last_ip})?(Y/n): ").strip().lower()
if use_last != 'n':
ip_port = last_ip
else:
ip_port = input("请输入设备 IP:端口(如 192.168.1.100:5555): ").strip()
else:
ip = input("请输入设备 IP(如 192.168.1.100): ").strip()
port = input("请输入端口号(默认 5555 可回车): ").strip() or "5555"
ip_port = f"{ip}:{port}"
try:
result = subprocess.run([adb_path, 'connect', ip_port],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if "connected" in result.stdout.lower():
print(f"✅ 已成功连接到:{ip_port}")
with open(LAST_IP_FILE, "w") as f:
f.write(ip_port)
return True
else:
print(f"连接失败:{result.stdout.strip() or result.stderr.strip()}")
except Exception as e:
print(f"连接出错: {e}")
return False
def select_apk_file():
"""弹出窗口选择 APK 文件"""
root = Tk()
root.withdraw()
root.attributes('-topmost', True)
apk_path = filedialog.askopenfilename(title="选择 APK 文件", filetypes=[("APK 文件", "*.apk")])
root.destroy()
return apk_path
def install_apk(adb_path, device_id, apk_path):
"""安装 APK 到指定设备"""
try:
result = subprocess.run([adb_path, '-s', device_id, 'install', apk_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
print(f"✅ APK 安装成功: {apk_path}")
else:
print(f"❌ APK 安装失败: {result.stderr.strip()}")
except Exception as e:
print(f"安装失败: {e}")
def main():
print("=== ADB 快捷安装工具(支持 USB 和 Wi-Fi)===")
adb_path = get_adb_path()
devices = get_connected_devices(adb_path)
if not devices:
print("未检测到 USB 设备,准备通过 Wi-Fi 连接设备...")
if not connect_via_wifi(adb_path):
input("连接失败,按回车键退出...")
return
devices = get_connected_devices(adb_path)
if not devices:
print("连接后仍未检测到设备。")
input("按回车键退出...")
return
while True:
devices = get_connected_devices(adb_path)
print("\n检测到以下设备:")
for idx, device in enumerate(devices):
print(f"{idx + 1}. {device}")
print(f"{len(devices) + 1}. 添加新的设备(输入 IP:端口)")
selected_device = None
try:
choice = int(input("请选择设备序号:")) - 1
if 0 <= choice < len(devices):
selected_device = devices[choice]
break
elif choice == len(devices):
if connect_via_wifi(adb_path):
continue
else:
print("连接失败,请重试。")
else:
print("无效选择,请输入有效的序号。")
except ValueError:
print("请输入数字序号。")
apk_path = select_apk_file()
if not apk_path:
print("未选择 APK 文件,操作取消。")
input("按回车键退出...")
return
if not os.path.exists(apk_path):
print(f"文件不存在:{apk_path}")
input("按回车键退出...")
return
print(f"开始安装 APK: {apk_path}")
install_apk(adb_path, selected_device, apk_path)
input("安装完成,按回车键退出...")
if __name__ == "__main__":
main()
3.效果演示
当电脑只连接到一个设备时,会自动打开文件夹让你选择。
当电脑只连接到多个设备时,会先选择哪个设备,在选择文件夹
下次执行时,会自动打开上次选择的文件夹