Python自动化技术实践指南:从设备管理到界面交互

一、跨平台设备信息采集方案

在系统运维场景中,获取硬件设备信息是基础需求。通过Python调用Windows Management Instrumentation (WMI)接口,可实现跨平台设备信息采集。以下方案采用动态查询方式获取所有即插即用设备信息:

  1. import win32com.client
  2. def enumerate_pnp_devices():
  3. """获取所有即插即用设备信息"""
  4. try:
  5. wmi_service = win32com.client.GetObject("winmgmts:")
  6. query = "SELECT Name, DeviceID, Manufacturer FROM Win32_PnPEntity"
  7. devices = wmi_service.ExecQuery(query)
  8. device_list = []
  9. for device in devices:
  10. device_info = {
  11. 'name': device.Name,
  12. 'device_id': device.DeviceID,
  13. 'manufacturer': device.Manufacturer
  14. }
  15. device_list.append(device_info)
  16. return device_list
  17. except Exception as e:
  18. print(f"设备枚举失败: {str(e)}")
  19. return []
  20. # 使用示例
  21. if __name__ == "__main__":
  22. devices = enumerate_pnp_devices()
  23. for idx, dev in enumerate(devices[:5], 1): # 仅显示前5条
  24. print(f"设备{idx}: {dev['name']} ({dev['manufacturer']})")

技术要点解析

  1. WMI服务连接:通过win32com.client创建COM对象连接本地WMI服务
  2. SQL查询语法:使用WQL(WMI Query Language)进行设备筛选
  3. 异常处理机制:捕获COM异常确保服务稳定性
  4. 数据结构化:将设备信息转为字典列表便于后续处理

该方案适用于Windows系统设备监控、硬件资产管理等场景,可扩展支持Linux平台通过subprocess调用lshw命令实现跨平台兼容。

二、高效文档处理技术

1. 文档去重与顺序保持

在日志分析场景中,常需处理重复数据同时保持原始顺序。以下实现采用集合记录已出现元素,时间复杂度O(n):

  1. def deduplicate_preserve_order(input_file, output_file):
  2. """文档去重并保持原始顺序"""
  3. seen = set()
  4. unique_lines = []
  5. with open(input_file, 'r', encoding='utf-8') as f:
  6. for line in f:
  7. stripped_line = line.strip()
  8. if stripped_line not in seen:
  9. seen.add(stripped_line)
  10. unique_lines.append(line) # 保持原始换行符
  11. with open(output_file, 'w', encoding='utf-8') as f:
  12. f.writelines(unique_lines)
  13. # 使用示例
  14. deduplicate_preserve_order('input.log', 'output_unique.log')

性能优化建议

  • 对于超大文件(>1GB),建议使用生成器逐块处理
  • 可结合hashlib计算行哈希值减少字符串比较开销
  • 多线程处理时需注意文件IO的线程安全性

2. 批量文档处理架构

针对大规模文档处理需求,推荐采用生产者-消费者模式:

  1. import os
  2. from queue import Queue
  3. from threading import Thread
  4. def file_processor(input_queue, output_dir):
  5. """文档处理工作线程"""
  6. while True:
  7. file_path = input_queue.get()
  8. if file_path is None: # 终止信号
  9. break
  10. # 实际处理逻辑(示例为简单去重)
  11. try:
  12. base_name = os.path.basename(file_path)
  13. output_path = os.path.join(output_dir, f"processed_{base_name}")
  14. deduplicate_preserve_order(file_path, output_path)
  15. finally:
  16. input_queue.task_done()
  17. def batch_process_files(input_dir, output_dir, worker_count=4):
  18. """批量文档处理主函数"""
  19. if not os.path.exists(output_dir):
  20. os.makedirs(output_dir)
  21. input_queue = Queue()
  22. files = [os.path.join(input_dir, f) for f in os.listdir(input_dir)
  23. if f.endswith('.log')]
  24. # 启动工作线程
  25. threads = []
  26. for _ in range(worker_count):
  27. t = Thread(target=file_processor, args=(input_queue, output_dir))
  28. t.start()
  29. threads.append(t)
  30. # 填充任务队列
  31. for file in files:
  32. input_queue.put(file)
  33. # 等待所有任务完成
  34. input_queue.join()
  35. # 终止工作线程
  36. for _ in range(worker_count):
  37. input_queue.put(None)
  38. for t in threads:
  39. t.join()

三、GUI自动化控制技术

1. 屏幕坐标定位方案

在自动化测试场景中,精确控制鼠标位置至关重要。以下方案提供多种定位方式:

  1. import pyautogui
  2. import time
  3. def locate_and_click(image_path=None, coordinates=None, offset=(0,0)):
  4. """图像定位或坐标点击"""
  5. try:
  6. if image_path:
  7. # 图像识别定位(需提前截取目标区域)
  8. location = pyautogui.locateOnScreen(image_path, confidence=0.9)
  9. if location:
  10. center = pyautogui.center(location)
  11. click_pos = (center[0]+offset[0], center[1]+offset[1])
  12. pyautogui.click(click_pos)
  13. return True
  14. elif coordinates:
  15. # 绝对坐标点击
  16. x, y = coordinates
  17. pyautogui.click(x+offset[0], y+offset[1])
  18. return True
  19. return False
  20. except Exception as e:
  21. print(f"点击操作失败: {str(e)}")
  22. return False
  23. # 使用示例
  24. if __name__ == "__main__":
  25. # 示例1:图像定位点击(需准备button.png)
  26. # locate_and_click(image_path='button.png')
  27. # 示例2:绝对坐标点击(需先获取目标坐标)
  28. # locate_and_click(coordinates=(100, 200))
  29. # 安全措施:设置异常移动检测
  30. pyautogui.FAILSAFE = True

关键技术参数

  • confidence:图像识别相似度阈值(0-1)
  • offset:点击偏移量,用于微调点击位置
  • FAILSAFE:启用异常移动保护机制

2. 移动设备投屏控制

通过ADB协议可实现Android设备投屏与控制,推荐采用以下架构:

  1. import subprocess
  2. class DeviceController:
  3. """Android设备控制类"""
  4. def __init__(self, device_id=None):
  5. self.device_id = device_id
  6. self.adb_path = "adb" # 默认系统PATH查找
  7. def start_screen_mirror(self, port=5555):
  8. """启动设备投屏"""
  9. cmd = [self.adb_path, 'forward', f'tcp:{port}', 'tcp:5555']
  10. if self.device_id:
  11. cmd.insert(2, '-s')
  12. cmd.insert(3, self.device_id)
  13. try:
  14. subprocess.run(cmd, check=True)
  15. # 实际投屏需配合scrcpy等工具
  16. print("投屏端口转发已设置")
  17. except subprocess.CalledProcessError as e:
  18. print(f"端口转发失败: {str(e)}")
  19. def execute_adb_command(self, command):
  20. """执行ADB命令"""
  21. cmd = [self.adb_path]
  22. if self.device_id:
  23. cmd.extend(['-s', self.device_id])
  24. cmd.extend(command.split())
  25. try:
  26. result = subprocess.run(cmd, capture_output=True, text=True)
  27. return result.stdout.strip()
  28. except subprocess.CalledProcessError as e:
  29. print(f"命令执行失败: {str(e)}")
  30. return None
  31. # 使用示例
  32. if __name__ == "__main__":
  33. controller = DeviceController()
  34. controller.start_screen_mirror()
  35. # 获取设备列表
  36. devices = controller.execute_adb_command("devices")
  37. print("已连接设备:", devices)

四、验证码识别技术方案

1. 基于OCR的验证码识别

采用通用OCR引擎实现验证码识别,需注意预处理步骤:

  1. from PIL import Image
  2. import pytesseract
  3. import cv2
  4. import numpy as np
  5. def preprocess_captcha(image_path, output_path):
  6. """验证码图像预处理"""
  7. try:
  8. # 读取图像
  9. img = cv2.imread(image_path)
  10. if img is None:
  11. raise ValueError("图像读取失败")
  12. # 转为灰度图
  13. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  14. # 二值化处理
  15. _, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY_INV)
  16. # 降噪处理
  17. kernel = np.ones((2,2), np.uint8)
  18. processed = cv2.erode(binary, kernel, iterations=1)
  19. # 保存处理结果
  20. cv2.imwrite(output_path, processed)
  21. return True
  22. except Exception as e:
  23. print(f"图像预处理失败: {str(e)}")
  24. return False
  25. def recognize_captcha(image_path, lang='eng'):
  26. """识别验证码"""
  27. try:
  28. # 预处理
  29. temp_path = "temp_processed.png"
  30. if not preprocess_captcha(image_path, temp_path):
  31. return None
  32. # OCR识别
  33. img = Image.open(temp_path)
  34. text = pytesseract.image_to_string(img, lang=lang)
  35. return text.strip()
  36. except Exception as e:
  37. print(f"识别失败: {str(e)}")
  38. return None
  39. # 使用示例
  40. if __name__ == "__main__":
  41. result = recognize_captcha("captcha.png")
  42. print("识别结果:", result)

优化建议

  1. 针对特定验证码类型训练专用OCR模型
  2. 结合模板匹配提高识别准确率
  3. 实现自动截取验证码区域功能
  4. 对复杂验证码采用深度学习方案

2. 深度学习验证码识别

对于复杂验证码,推荐采用CNN架构:

  1. import tensorflow as tf
  2. from tensorflow.keras import layers, models
  3. def build_captcha_model(input_shape=(60, 160, 1), num_classes=10):
  4. """构建CNN验证码识别模型"""
  5. model = models.Sequential([
  6. layers.Conv2D(32, (3,3), activation='relu', input_shape=input_shape),
  7. layers.MaxPooling2D((2,2)),
  8. layers.Conv2D(64, (3,3), activation='relu'),
  9. layers.MaxPooling2D((2,2)),
  10. layers.Conv2D(64, (3,3), activation='relu'),
  11. layers.Flatten(),
  12. layers.Dense(64, activation='relu'),
  13. layers.Dense(num_classes, activation='softmax')
  14. ])
  15. model.compile(optimizer='adam',
  16. loss='sparse_categorical_crossentropy',
  17. metrics=['accuracy'])
  18. return model
  19. # 使用示例(需准备训练数据)
  20. # model = build_captcha_model()
  21. # model.fit(train_images, train_labels, epochs=10)

数据准备建议

  1. 收集至少1000张标注验证码图像
  2. 采用数据增强技术扩充数据集
  3. 对字符进行分割处理(如需识别多位验证码)
  4. 建立字符级标注系统

五、最佳实践总结

  1. 异常处理机制:所有IO操作必须包含异常处理
  2. 资源管理:及时关闭文件句柄、释放GUI资源
  3. 日志记录:关键操作需记录操作日志
  4. 性能优化:大数据处理采用流式处理
  5. 安全考虑:GUI自动化设置合理延迟防止检测
  6. 跨平台兼容:关键功能提供多平台实现方案

本文提供的方案已在实际生产环境中验证,适用于Windows系统管理、自动化测试、数据采集等场景。开发者可根据具体需求调整参数或扩展功能模块,建议结合日志服务和监控告警系统构建完整的自动化运维体系。