🐍奋斗吧〆少年⁶ᴳ👻
type: channel
link: https://blog.cutekitty.cn/
description: 🤷‍♂️INFJ🎮
items: Python一键完成奥智利AZL-212C系列分机刷机示例
items: Python异步协程示例
items: Python调用Yolov8示例
items: Python调用易键鼠示例
items: Python调用WindowsApi实现各种操作示例
items: Python调用VMware虚拟机示例
items: Python进程守护示例
items: Python多线程示例
items: Python创建邮局服务示例
items: Python调用乐玩插件示例

Python一键完成奥智利AZL-212C系列分机刷机示例
type: item
date: 2025-06-25T21:33:00+08:00
description: # -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'app.ui' ## ## Created by: Qt User Interface Compiler version 6.6.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QLabel, QMainWindow, QPushButton, QSizePolicy, QStatusBar, QTextEdit, QWidget) class Ui_MainWindow(object): def setupUi(self, MainWindow): if not MainWindow.objectName(): MainWindow.setObjectName(u"MainWindow") MainWindow.resize(611, 630) MainWindow.setStyleSheet(u"font: 9pt \"Microsoft YaHei UI\";") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(u"centralwidget") self.comboBox_networkcard = QComboBox(self.centralwidget) self.comboBox_networkcard.setObjectName(u"comboBox_networkcard") self.comboBox_networkcard.setGeometry(QRect(90, 10, 260, 22)) self.label_networkcard = QLabel(self.centralwidget) self.label_networkcard.setObjectName(u"label_networkcard") self.label_networkcard.setGeometry(QRect(20, 10, 53, 20)) self.label_class = QLabel(self.centralwidget) self.label_class.setObjectName(u"label_class") self.label_class.setGeometry(QRect(20, 50, 53, 20)) self.comboBox_class = QComboBox(self.centralwidget) self.comboBox_class.setObjectName(u"comboBox_class") self.comboBox_class.setGeometry(QRect(90, 50, 261, 22)) self.textEdit_networkadapter = QTextEdit(self.centralwidget) self.textEdit_networkadapter.setObjectName(u"textEdit_networkadapter") self.textEdit_networkadapter.setGeometry…

Python异步协程示例
type: item
date: 2025-06-25T21:23:00+08:00
description: """ import asyncio async def func(): print("喵") if __name__ == '__main__': # # 协程对象要想运行，必须借助于event_loop # # 拿到协程对象 f = func() # # 拿到事件循环 # event_loop = asyncio.get_event_loop() # # event_loop执行协程对象，直到对象内的内容执行完毕为止. # event_loop.run_until_complete(f) asyncio.run(f) """ ''' import asyncio import time async def func1(): print("我是func1开始") await asyncio.sleep(1) print("我是func1结束") async def func2(): print("我是func2开始") await asyncio.sleep(2) print("我是func2结束") async def func3(): print("我是func3开始") await asyncio.sleep(3) print("我是func3结束") if __name__ == '__main__': start = time.time() f1 = func1() f2 = func2() f3 = func3() # 将三个任务放在一起，组合成任务队列 tasks = [f1, f2, f3] asyncio.run(asyncio.wait(tasks)) print(time.time()-start) ''' ''' import asyncio import time async def download(url, t): print("开始下载了") await asyncio.sleep(t) print("下载完了") async def main(): urls = [ 'http://www.baidu.com', 'http://www.abab.com', 'http://www.lll.com', ] tasks = [] for url in urls: task = asyncio.create_task(download(url, 3)) tasks.append(task) await asyncio.wait(tasks) if __name__ == '__main__': asyncio.run(main()) ''' ''' import asyncio async def func1(): print("我是func1开始") await asyncio.sleep(1) print("我是func1结束") return 'func1的返回值' async def func2(): print("我是func2开始") await asyncio.sleep(2) print("我是func2结束") return 'func2的返回值' async def func3(): print("我是func3开始") await asyncio.sleep(3) print("我是func3结束") return 'func3的返回值' async def main(): f1 = func1() f2 = func2() f3 = func3() tasks = [asyncio.create_task(f1), asyncio.create_task(f3), asyncio.create_task(f2)] done, pending = await asyncio.wait(tasks) for res in done: print(res.result()) res = await asyncio.gather(*tasks) print(res) if __name__ == '__main__': asyncio.run(main()) ''' import asyncio import aiohttp import aiofiles async def download(url): print(f'开始下载{url}') file_name = url.split('/')[-1] async with aiohttp.ClientSession() as session: async with session.get(url) as res: content = await res.content.read() async with aiofiles.o…

Python调用Yolov8示例
type: item
date: 2025-06-25T21:17:00+08:00
description: import time import fastdeploy as fd import cv2 class YoloV8Prediction: def __init__(self, ModelPath: str, PreheatingImagesPath: str): option = fd.RuntimeOption() # 切换使用CPU/GPU # option.use_cpu() option.use_gpu() # 切换不同后端 # option.use_paddle_infer_backend() # option.use_paddle_lite_backend() # option.use_paddle_backend() option.use_openvino_backend() # option.use_ort_backend() option.use_trt_backend() # option.use_poros_backend() self.yolov8 = fd.vision.detection.YOLOv8(ModelPath, runtime_option=option) self.yolov8.preprocessor.size = [640, 640] img = cv2.imread(PreheatingImagesPath) s = time.time() for i in range(100): self.yolov8.predict(img) print(f'模型预热成功，预测100张图片耗时{time.time() - s}秒') def Start_Prediction(self, Images: str): return self.yolov8.predict(Images)from ultralytics import YOLO import torch import glob import os import xml.etree.ElementTree as ET import random import shutil import time from window.windowclass_en import WindowManager import cv2 import Draw.D3Gui from yolov8.YoloV8_Prediction import YoloV8Prediction class YoloV8: def __init__(self, ModelPath: str, ParentWindowHandle, WindowClassName: str, WindowTitle: str, PreheatingImagesPath: str, Mode: int = 1): """ 使用YOLOV8时常用的函数，mode为0时为训练模型，为1时为预测模式（训练和预测的环境不一样，训练支支持64位python。训练是cuda+torch+安装ultralytics，预测是TensorRT+fastdeploy） :param ModelPath: str,模型路径，训练模式为pt模型，预测模式为onnx模型 :param ParentWindowHandle: int，父窗口句柄 :param WindowClassName: str，窗口类名 :param WindowTitle: str，窗口标题 :param PreheatingImagesPath: str，用于预热预测模型的图片路径 :param Mode: int，运行模式（训练/预测） """ self.mode = Mode self.window = WindowManager() self.handle = self.window.Find_Windows(ParentWindowHandle, WindowClassName, WindowTitle) if Mode == 0: self.yolo = YOLO(model=ModelPath) elif Mode == 1: self.yolo = YoloV8Prediction(ModelPath, PreheatingImagesPath) pass @staticmethod # 转换一个xml文件为txt def single_xml_to_txt(xml_file, class_names): tree = ET.parse(xml_file) root = tree.getroot() # 保存txt文件路径 text_dir, xml_name = os.path.split(xml_file) txt_name …

Python调用易键鼠示例
type: item
date: 2025-06-25T21:15:00+08:00
description: # -*- coding: utf-8 -*- import ctypes import os import time from ctypes import wintypes code_dict = { "1": 49, "2": 50, "3": 51, "4": 52, "5": 53, "6": 54, "7": 55, "8": 56, "9": 57, "0": 48, "-": 189, "=": 187, "back": 8, "a": 65, "b": 66, "c": 67, "d": 68, "e": 69, "f": 70, "g": 71, "h": 72, "i": 73, "j": 74, "k": 75, "l": 76, "m": 77, "n": 78, "o": 79, "p": 80, "q": 81, "r": 82, "s": 83, "t": 84, "u": 85, "v": 86, "w": 87, "x": 88, "y": 89, "z": 90, "ctrl": 17, "alt": 18, "shift": 16, "win": 91, "space": 32, "cap": 20, "tab": 9, "~": 192, "esc": 27, "enter": 13, "up": 38, "down": 40, "left": 37, "right": 39, "option": 93, "print": 44, "delete": 46, "home": 36, "end": 35, "pgup": 33 , "pgdn": 34, "f1": 112, "f2": 113, "f3": 114, "f4": 115, "f5": 116, "f6": 117, "f7": 118, "f8": 119, "f9": 120, "f10": 121, "f11": 122, "f12": 123, "[": 219, "]": 221, "\\": 220, ";": 186, "'": 222, ",": 188, ".": 190, "/": 191, } class YJS(): def __init__(self, w, h, move_flag=0, KeyDelay=None): # 初始化参数 self.w, self.h = w, h self.move_flag = move_flag self.KeyDelay = KeyDelay # 初始化易建鼠dll VID, PID = 0xC216, 0x0301 __path = os.getcwd() + os.path.sep + "msdk.dll" self.objdll = ctypes.windll.LoadLibrary(__path) # 注册dll self.objdll.M_Open_VidPid.restype = wintypes.LPHANDLE self.hdl = self.objdll.M_Open_VidPid(VID, PID) # 获取usb键鼠 self.__ResolutionUsed() if self.hdl == -1: raise "打开失败" # 设置鼠标轨迹 self.__EnableRealMouse(self.move_flag) # 设置键盘点击延迟随机 self.__EnableRealKeypad(KeyDelay) # 设置随机延迟 # self.__ResolutionUsed() def __del__(self): self.objdll.M_ReleaseAllKey(self.hdl) def __ResolutionUsed(self): # 如果使用绝对移动,则需要初始化分辨率 if self.move_flag == 1: # hdl = ctypes.c_int(self.hdl) self.objdll.M_ResolutionUsed(self.hdl, self.w, self.h) def GetSn(self): len_ = wintypes.DWORD() buf = wintypes.CHAR() self.objdll.M_GetDevSn(self.hdl,ctypes.byref(len_),ctypes.byref(buf)) print(len_.value) def __EnableRealMouse(self, move_flag: int): # 默认每次移动100-127个像素,时间间隔10-20ms self.move_flag = move_flag def __EnableReal…

Python调用WindowsApi实现各种操作示例
type: item
date: 2025-06-25T21:13:00+08:00
description: import time from ctypes import wintypes import ctypes import win32gui import win32con import win32ui import cv2 import numpy as np class WindowManager: @staticmethod def Capture_Win32_Gpu(handle: int, model: int = 3): """ 通过win32方式截图，并且无视硬件加速 https://stackoverflow.com/questions/19695214/screenshot-of-inactive-window-printwindow-win32gui """ ctypes.windll.user32.SetProcessDPIAware() # 抑制缩放 rect = win32gui.GetWindowRect(handle) width, height = rect[2] - rect[0], rect[3] - rect[1] hwnd_dc = win32gui.GetWindowDC(handle) mfc_dc = win32ui.CreateDCFromHandle(hwnd_dc) save_dc = mfc_dc.CreateCompatibleDC() save_bit_map = win32ui.CreateBitmap() save_bit_map.CreateCompatibleBitmap(mfc_dc, width, height) save_dc.SelectObject(save_bit_map) ctypes.windll.user32.PrintWindow(handle, save_dc.GetSafeHdc(), model) # 如果仍然是黑屏，尝试修改数字 ‘3’ (从0开始...) bmpinfo = save_bit_map.GetInfo() bmpstr = save_bit_map.GetBitmapBits(True) capture = np.frombuffer(bmpstr, dtype=np.uint8).reshape((bmpinfo["bmHeight"], bmpinfo["bmWidth"], 4)) capture = np.ascontiguousarray(capture)[..., :-1] win32gui.DeleteObject(save_bit_map.GetHandle()) save_dc.DeleteDC() mfc_dc.DeleteDC() win32gui.ReleaseDC(handle, hwnd_dc) capture = cv2.cvtColor(capture, cv2.COLOR_RGBA2RGB) return capture @staticmethod def Get_Handle(): """ 取窗口句柄 :return: int,窗口句柄 """ return win32gui.GetForegroundWindow() @staticmethod def Get_Window_Position_And_Size(handle): """ 窗口取位置和大小 :param handle: int,窗口句柄 :return: """ return win32gui.GetWindowRect(handle) class WindowRect(ctypes.Structure): _fields_ = [ ("left", ctypes.c_long), ("top", ctypes.c_long), ("right", ctypes.c_long), ("bottom", ctypes.c_long) ] def __init__(self): """ 调用Windows官方API实现对window的操作 """ self.user32 = ctypes.windll.user32 self.kernel32 = ctypes.windll.kernel32 # self.GetLastError = ctypes.windll.kernel32.GetLastError() self.gdi32 = ctypes.WinDLL("Gdi32.dll") def Find_Windows(self, parent_handle: int = None, class_name: str = None, window_title: str = None): """ 模糊遍历窗口 :param p…

Python调用VMware虚拟机示例
type: item
date: 2025-06-25T21:12:00+08:00
description: import os import subprocess class VM: def __init__(self, path): os.putenv("path", path) def run_command(self, command): # 取DOS执行结果 """运行cmd命令""" result = subprocess.run(command, capture_output=True, shell=True, encoding='gbk') return result.stdout def StartVirtualMachine(self, VirtualMachinePath: str, gui: bool): """启动指定虚拟机""" if gui: command = f'vmrun.exe -T ws start "{VirtualMachinePath}" gui' else: command = f'vmrun.exe -T ws start "{VirtualMachinePath}" nogui' return self.run_command(command) if __name__ == '__main__': vm = VM(r'E:\VMwareWorkstation') vm.StartVirtualMachine(r"D:\WinXp_52Pojie_2.0\WinXp_52Pojie_2.0.vmx", True)

Python进程守护示例
type: item
date: 2025-06-25T21:11:00+08:00
description: import base64 import io import subprocess import psutil from datetime import datetime import os from pathlib import Path import win32com.client import win32process import cv2 import numpy as np import win32ui import ctypes import win32gui import win32con import win32api import time from PIL import Image # 将Base64数据解码为图片 def base64_to_image(base64_data): """base64_png""" image_data = base64.b64decode(base64_data) image = Image.open(io.BytesIO(image_data)) return image def find_template(screenshot, template_path, threshold=0.8): """在截图中查找模板图片，返回匹配位置""" # 读取模板图片 template = cv2.imread(template_path, 0) if template is None: print(f"无法读取模板图片: {template_path}") return None # 转换截图为灰度图 screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY) # 模板匹配 result = cv2.matchTemplate(screenshot_gray, template, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) # 如果匹配度超过阈值，返回中心点坐标 if max_val >= threshold: h, w = template.shape center_x = max_loc[0] + w // 2 center_y = max_loc[1] + h // 2 return int(center_x), int(center_y), max_val else: print(f"未找到匹配项，最高匹配度: {max_val:.2f}") return None def click_in_window(hwnd, x, y): """在指定窗口的相对坐标处执行鼠标单击""" if not hwnd: return False # 获取窗口位置和大小 left, top, right, bottom = win32gui.GetClientRect(hwnd) window_width = right - left window_height = bottom - top # 检查坐标是否在窗口内 if x < 0 or x >= window_width or y < 0 or y >= window_height: print(f"坐标 ({x}, {y}) 超出窗口范围 ({window_width}, {window_height})") return False # 将客户端坐标转换为屏幕坐标 screen_x, screen_y = win32gui.ClientToScreen(hwnd, (x, y)) # 激活窗口 win32gui.SetForegroundWindow(hwnd) time.sleep(0.1) # 等待窗口激活 # 执行鼠标单击 win32api.SetCursorPos((screen_x, screen_y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, screen_x, screen_y, 0, 0) time.sleep(0.05) # 模拟真实点击的按下时间 win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, screen_x, screen_y, 0, 0) return True def Capture_Win32_Gpu(handle: int, model: int = 3): """ 通过win32方式截图，并且无视硬件加速 https://stackoverflow.com/questions/19695214/scre…

Python多线程示例
type: item
date: 2025-06-25T21:08:00+08:00
description: # -*- coding: utf-8 -*- import ctypes import sys import threading import time class _MyThread(threading.Thread): def __init__(self, target=None, args=(), kwargs=None, daemon=True): super(_MyThread, self).__init__(target=target, args=args, kwargs=kwargs, daemon=daemon) self.flag = threading.Event() # 虽然能停止线,会有不可预知的问题 def stop(self): print(f"停止线程 {self.name}") if not self.is_alive(): return exc = ctypes.py_object(SystemExit) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(self.ident), exc) if res == 0: raise ValueError("找不到线程ID") elif res > 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(self.ident, None) raise SystemError("线程已停止") class MyThread(threading.Thread): dict_ = [{"kill": False} for i in range(1000)] def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, daemon=True, dict_={}): threading.Thread.__init__(self, group=group, target=target, name=name, args=args, kwargs=kwargs, daemon=daemon) if dict_: self.killed = dict_ else: self.killed = {"kill": False} def start(self): print(f"开启线程{self}") self.__run_backup = self.run self.run = self.__run threading.Thread.start(self) def __run(self): sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup def globaltrace(self, frame, event, arg): if event == 'call': return self.localtrace else: return None def localtrace(self, frame, event, arg): if self.killed["kill"]: if event == 'line': if self.killed["kill"] == 1: raise SystemExit() elif self.killed["kill"] == 2: while self.killed["kill"]: time.sleep(0.1) return self.localtrace def stop(self): print(f"停止线程{self}") self.killed["kill"] = 1 def pause(self): print(f"暂停线程{self}") self.killed["kill"] = 2 def resume(self): print(f"恢复线程{self}") self.killed["kill"] = False def test_func(num): for i in range(num): time.sleep(1) print(i) if __name__ == '__main__': # 第一种线程 # t = _MyThread(target=test_func,args=(100,)) # t.start() # time.sleep(5) # t.stop() # input() # # 第二种线程 t = MyThread(target=test_func, args=(100,)) t.…

Python创建邮局服务示例
type: item
date: 2025-06-25T21:07:00+08:00
description: from email.parser import Parser from email.header import decode_header from email.utils import parseaddr from lxml import etree import requests import poplib class PopMail: def __init__(self, email, password): # 输入邮件地址, 口令和POP3服务器地址: self.email = email self.password = password self.pop3_server = "mail.recolte-cn.cn" self.header = { 'User-Agent': 'Apipost client Runtime/+https://www.apipost.cn/', 'Content-Type': 'application/x-www-form-urlencoded', } def connect(self): # 连接到POP3服务器: self.server = poplib.POP3(self.pop3_server) # 可以打开或关闭调试信息: self.server.set_debuglevel(1) # 可选:打印POP3服务器的欢迎文字: print(self.server.getwelcome().decode('utf-8')) # 身份认证: self.server.user(self.email) self.server.pass_(self.password) def get_msg(self): # stat()返回邮件数量和占用空间: print('Messages: %s. Size: %s' % self.server.stat()) # list()返回所有邮件的编号: resp, mails, octets = self.server.list() # 可以查看返回的列表类似[b'1 82923', b'2 2184', ...] print(mails) # 获取最新一封邮件, 注意索引号从1开始: index = len(mails) resp, lines, octets = self.server.retr(index) # lines存储了邮件的原始文本的每一行, # 可以获得整个邮件的原始文本: msg_content = b'\r\n'.join(lines).decode('utf-8') # 稍后解析出邮件: self.msg = Parser().parsestr(msg_content) # 可以根据邮件索引号直接从服务器删除邮件: # server.dele(index) # 关闭连接: self.server.quit() # indent用于缩进显示: def print_info(self, msg, indent=0): if indent == 0: for header in ['From', 'To', 'Subject']: value = msg.get(header, '') if value: if header == 'Subject': value = self.decode_str(value) else: hdr, addr = parseaddr(value) name = self.decode_str(hdr) value = u'%s <%s>' % (name, addr) print('%s%s: %s' % (' ' * indent, header, value)) if (msg.is_multipart()): parts = msg.get_payload() for n, part in enumerate(parts): print('%spart %s' % (' ' * indent, n)) print('%s--------------------' % (' ' * indent)) self.print_info(part, indent + 1) else: content_type = msg.get_content_type() if content_type == 'text/plain' or content_type == 'text/html': content = msg.get_payload(decode=True) charset = self.guess_charset(msg) if charset: content = content.decode(c…

Python调用乐玩插件示例
type: item
date: 2025-06-25T21:05:00+08:00
description: # -*- coding: utf-8 -*- import os from comtypes.client import CreateObject class LW: def __init__(self): self.lw = None try: self.lw = CreateObject('lw.lwsoft3') print('本机系统中已经安装乐玩插件，版本为:', self.Version()) except: print('本机并未安装乐玩，正在注册调用') cmd = "regsvr32 -s lw.dll" os.system(cmd) self.lw = CreateObject('lw.lwsoft3') print('本机系统中已经安装乐玩插件，版本为:', self.Version()) def Version(self): return self.lw.Ver() if __name__ == '__main__': lw = LW()