Python subprocess 使用(一)
Python subprocess 使用(一)
本文主要讲下 subprocess 的简单使用.
1: 通过subprocess 获取设备信息
import subprocess
def get_android_device_info():
# 使用adb命令获取设备信息
result = subprocess.run(['adb', 'devices', '-l'], capture_output=True, text=True)
output = result.stdout.strip()
# 解析设备信息
devices = []
lines = output.split('\n')
for line in lines[1:]:
if 'device' in line:
device_info = line.split()
device = {
'serial': device_info[0],
'model': device_info[4],
'device': device_info[5],
'product': device_info[3],
'transport_id': device_info[6]
}
devices.append(device)
return devices
# 调用函数获取设备信息
devices = get_android_device_info()
for device in devices:
print('Serial:', device['serial'])
print('Model:', device['model'])
print('Device:', device['device'])
print('Product:', device['product'])
print('Transport ID:', device['transport_id'])
print('--')
具体的adb 执行结果如下:
List of devices attached
6b4a96b2 device usb:1-1 product:LeMax2_WW model:LEX820 device:le_x2 transport_id:43
2: 通过subprocess 获取屏幕分辨率
def get_device_physical():
command = 'adb shell wm size'
result = subprocess.check_output(command.split()).decode().strip()
resolution = result.split()[-1]
return resolution
print('设备分辨率:' + str(get_device_physical()))
3: 获取设备系统日志
def capture_android_log():
# 使用adb命令获取Android系统日志
command = "adb logcat"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 读取日志输出
while True:
line = process.stdout.readline().decode("utf-8")
if line:
print(line.strip())
else:
break
# 调用函数抓取Android系统日志
capture_android_log()