优化后台截图功能

This commit is contained in:
Your Name committed 2025-12-31 11:55:01 +08:00
1 parent 223c127e11
commit ace3bbfa04
70 files changed
+4392 -871

No files matched your search

View File
Whitespace-only changes.
+2
View File
@@ -126,3 +126,5 @@ python region_selector.py path/to/image.png
- 白色像素阈值:RGB值都≥240的像素被认为是白色
View File
Whitespace-only changes.
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""分析优化效果"""
import sys
import os
import re
from datetime import datetime
if sys.platform == 'win32':
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def main():
log_file = "logs/unified_2025-12-31.log"
if not os.path.exists(log_file):
print("日志文件不存在")
return
with open(log_file, 'r', encoding='utf-8', errors='replace') as f:
lines = f.readlines()
print("=" * 60)
print("优化效果分析")
print("=" * 60)
print()
# 1. 检查服务启动
service_started = False
for line in lines:
if '截图服务' in line and '已启动' in line:
service_started = True
print("✅ 服务已启动")
# 提取时间
time_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if time_match:
print(f" 启动时间: {time_match.group(1)}")
break
if not service_started:
print("❌ 服务未启动")
return
# 2. 分析服务启动后的截图性能
service_start_time = None
screenshot_times_after_service = []
for i, line in enumerate(lines):
if '截图服务' in line and '已启动' in line:
time_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if time_match:
h, m, s = map(int, time_match.group(1).split(':'))
service_start_time = h * 3600 + m * 60 + s
print(f" 服务启动时间戳: {service_start_time}")
break
if service_start_time:
# 分析服务启动后的截图耗时
for line in lines:
if 'screenshot_elapsed_seconds' in line:
time_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if time_match:
h, m, s = map(int, time_match.group(1).split(':'))
log_time = h * 3600 + m * 60 + s
if log_time >= service_start_time:
elapsed_match = re.search(r'screenshot_elapsed_seconds=([\d.]+)', line)
if elapsed_match:
elapsed = float(elapsed_match.group(1))
screenshot_times_after_service.append(elapsed)
if screenshot_times_after_service:
print()
print("服务启动后的截图性能:")
print(f" 次数: {len(screenshot_times_after_service)}")
print(f" 平均耗时: {sum(screenshot_times_after_service) / len(screenshot_times_after_service):.2f}秒")
print(f" 最短耗时: {min(screenshot_times_after_service):.2f}秒")
print(f" 最长耗时: {max(screenshot_times_after_service):.2f}秒")
# 分析快速响应(可能是缓存命中)
fast_responses = [t for t in screenshot_times_after_service if t < 0.5]
if fast_responses:
print(f"\n ✅ 发现 {len(fast_responses)} 次快速响应(< 0.5秒)")
print(f" 说明缓存可能生效")
else:
print(f"\n ⚠️ 未发现快速响应(< 0.5秒)")
print(f" 可能原因:缓存未命中或服务未正常工作")
# 3. 检查代码集成
print()
print("=" * 60)
print("代码集成检查")
print("=" * 60)
# 检查 Underlying_Operations.py
if os.path.exists("Underlying_Operations.py"):
with open("Underlying_Operations.py", 'r', encoding='utf-8') as f:
content = f.read()
if 'use_service' in content and 'ScreenshotService' in content:
print("✅ Underlying_Operations.py 已支持服务模式")
else:
print("❌ Underlying_Operations.py 未支持服务模式")
print()
print("=" * 60)
print("结论")
print("=" * 60)
if service_started:
if screenshot_times_after_service:
avg = sum(screenshot_times_after_service) / len(screenshot_times_after_service)
if avg < 1.0:
print("✅ 优化生效!平均耗时 < 1秒")
elif avg < 2.0:
print("⚠️ 优化部分生效,平均耗时 1-2秒")
print(" 可能原因:缓存未完全生效")
else:
print("❌ 优化未生效,平均耗时 >= 2秒")
print(" 可能原因:")
print(" 1. 缓存未命中")
print(" 2. 服务未正常工作")
print(" 3. 某些调用未使用服务模式")
else:
print("⚠️ 服务已启动,但未找到截图耗时数据")
else:
print("❌ 服务未启动,需要重新运行程序")
if __name__ == '__main__':
main()
+136
View File
@@ -0,0 +1,136 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""分析日志中的截图耗时,评估优化效果"""
import sys
import os
import re
from datetime import datetime
# 设置UTF-8输出
if sys.platform == 'win32':
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
def analyze_log_file(log_path):
"""分析日志文件"""
if not os.path.exists(log_path):
print(f"日志文件不存在: {log_path}")
return
print("=" * 60)
print("截图性能分析")
print("=" * 60)
print()
# 读取日志文件
try:
with open(log_path, 'r', encoding='utf-8', errors='replace') as f:
lines = f.readlines()
except Exception as e:
print(f"读取日志文件失败: {e}")
return
# 查找截图相关的日志
screenshot_times = []
service_started = False
for line in lines:
# 检查服务启动
if '截图服务' in line or 'ScreenshotService' in line or '后台截图' in line:
service_started = True
print(f"✅ 发现服务启动日志: {line.strip()[:100]}")
# 查找截图耗时
if 'screenshot_elapsed_seconds' in line:
# 提取耗时
match = re.search(r'screenshot_elapsed_seconds=([\d.]+)', line)
if match:
elapsed = float(match.group(1))
screenshot_times.append(elapsed)
# 查找截图成功日志
if '[截图]' in line and '成功' in line:
# 尝试提取时间戳
timestamp_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if timestamp_match:
pass # 可以用于分析时间间隔
# 分析结果
print(f"\n服务启动状态: {'✅ 已启动' if service_started else '❌ 未启动'}")
print()
if screenshot_times:
print(f"截图耗时统计(共 {len(screenshot_times)} 次):")
print(f" 平均耗时: {sum(screenshot_times) / len(screenshot_times):.2f} 秒")
print(f" 最短耗时: {min(screenshot_times):.2f} 秒")
print(f" 最长耗时: {max(screenshot_times):.2f} 秒")
print()
# 分析优化效果
avg_time = sum(screenshot_times) / len(screenshot_times)
if service_started:
if avg_time < 0.5:
print("✅✅✅ 优化效果显著!平均耗时 < 0.5秒")
elif avg_time < 1.0:
print("✅✅ 优化效果良好!平均耗时 < 1秒")
elif avg_time < 2.0:
print("✅ 优化效果一般,平均耗时 < 2秒")
else:
print("⚠️ 优化效果不明显,平均耗时 >= 2秒")
else:
print("⚠️ 服务未启动,这是优化前的性能")
print(" 预期优化后: 缓存命中 < 0.01秒,缓存未命中 0.5-1秒")
else:
print("未找到截图耗时数据")
# 查找最近的截图日志
print()
print("最近的截图日志(最后5条):")
screenshot_logs = [line for line in lines if '[截图]' in line and '成功' in line]
for log in screenshot_logs[-5:]:
print(f" {log.strip()[:150]}")
def main():
"""主函数"""
# 查找最新的日志文件
log_dir = "logs"
if not os.path.exists(log_dir):
print(f"日志目录不存在: {log_dir}")
return
# 查找最新的 unified_*.log 文件
log_files = [f for f in os.listdir(log_dir) if f.startswith('unified_') and f.endswith('.log')]
if not log_files:
print("未找到 unified_*.log 文件")
return
# 按修改时间排序
log_files.sort(key=lambda f: os.path.getmtime(os.path.join(log_dir, f)), reverse=True)
latest_log = os.path.join(log_dir, log_files[0])
print(f"分析日志文件: {latest_log}")
print()
analyze_log_file(latest_log)
print()
print("=" * 60)
print("分析完成")
print("=" * 60)
# 建议
print()
print("建议:")
print("1. 如果服务未启动,请重新运行程序(代码已更新)")
print("2. 如果服务已启动但性能未提升,检查缓存是否生效")
print("3. 查看日志中是否有服务启动的错误信息")
if __name__ == '__main__':
main()
+287
View File
@@ -0,0 +1,287 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""检查截图优化是否生效"""
import sys
import os
import re
from datetime import datetime
# 设置UTF-8输出
if sys.platform == 'win32':
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def analyze_latest_log():
"""分析最新日志"""
log_dir = "logs"
if not os.path.exists(log_dir):
print("日志目录不存在")
return None
# 查找最新的 unified_*.log 文件
log_files = [f for f in os.listdir(log_dir) if f.startswith('unified_') and f.endswith('.log')]
if not log_files:
print("未找到日志文件")
return None
log_files.sort(key=lambda f: os.path.getmtime(os.path.join(log_dir, f)), reverse=True)
latest_log = os.path.join(log_dir, log_files[0])
print(f"分析日志: {latest_log}")
print()
try:
with open(latest_log, 'r', encoding='utf-8', errors='replace') as f:
lines = f.readlines()
except Exception as e:
print(f"读取日志失败: {e}")
return None
return lines, latest_log
def check_service_startup(lines):
"""检查服务是否启动"""
print("=" * 60)
print("1. 检查服务启动状态")
print("=" * 60)
service_started = False
service_logs = []
for line in lines:
if '截图服务' in line or 'ScreenshotService' in line or '后台截图' in line:
service_started = True
service_logs.append(line.strip())
if service_started:
print("✅ 服务已启动")
print("\n服务启动日志:")
for log in service_logs[:3]: # 显示前3条
print(f" {log[:150]}")
else:
print("❌ 服务未启动")
print(" 日志中未找到服务启动记录")
print(" 可能原因:")
print(" 1. 程序还未重新运行(需要运行新代码)")
print(" 2. 服务启动时发生异常(被静默捕获)")
return service_started
def analyze_screenshot_performance(lines, service_started):
"""分析截图性能"""
print("\n" + "=" * 60)
print("2. 分析截图性能")
print("=" * 60)
# 提取截图耗时
screenshot_times = []
screenshot_logs = []
for line in lines:
# 查找截图耗时
if 'screenshot_elapsed_seconds' in line:
match = re.search(r'screenshot_elapsed_seconds=([\d.]+)', line)
if match:
elapsed = float(match.group(1))
screenshot_times.append(elapsed)
screenshot_logs.append((elapsed, line.strip()[:100]))
# 查找截图成功日志(用于分析时间间隔)
if '[截图]' in line and ('成功' in line or '✓' in line):
timestamp_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if timestamp_match:
screenshot_logs.append(('log', line.strip()[:100]))
if screenshot_times:
avg_time = sum(screenshot_times) / len(screenshot_times)
min_time = min(screenshot_times)
max_time = max(screenshot_times)
print(f"截图耗时统计(共 {len(screenshot_times)} 次):")
print(f" 平均耗时: {avg_time:.2f} 秒")
print(f" 最短耗时: {min_time:.2f} 秒")
print(f" 最长耗时: {max_time:.2f} 秒")
print()
# 分析优化效果
if service_started:
print("优化效果分析(服务已启动):")
if avg_time < 0.5:
print(" ✅✅✅ 优化效果非常显著!平均耗时 < 0.5秒")
print(" 说明缓存机制正常工作,响应速度大幅提升")
elif avg_time < 1.0:
print(" ✅✅ 优化效果良好!平均耗时 < 1秒")
print(" 说明服务正常工作,性能有明显提升")
elif avg_time < 2.0:
print(" ✅ 优化效果一般,平均耗时 < 2秒")
print(" 可能原因:缓存未命中,需要等待后台截图")
else:
print(" ⚠️ 优化效果不明显,平均耗时 >= 2秒")
print(" 可能原因:")
print(" 1. 缓存未生效")
print(" 2. 后台截图间隔设置过长")
print(" 3. 服务未正常工作")
else:
print("优化效果分析(服务未启动):")
print(" ⚠️ 这是优化前的性能")
print(f" 平均耗时: {avg_time:.2f} 秒(优化前)")
print(" 预期优化后:")
print(" - 缓存命中: < 0.01秒")
print(" - 缓存未命中: 0.5-1秒")
print(" - 平均耗时: 0.3-0.8秒")
# 显示最近的截图耗时
print("\n最近的截图耗时(最后5次):")
recent_times = [t for t, _ in screenshot_logs if isinstance(t, float)][-5:]
for i, t in enumerate(recent_times, 1):
status = "✅" if t < 1.0 else "⚠️" if t < 2.0 else "❌"
print(f" {status} 第{i}次: {t:.2f}秒")
else:
print("未找到截图耗时数据")
print("可能原因:日志格式不同或未记录耗时")
def check_cache_effectiveness(lines):
"""检查缓存是否生效"""
print("\n" + "=" * 60)
print("3. 检查缓存效果")
print("=" * 60)
# 查找连续的截图操作,分析时间间隔
screenshot_timestamps = []
for line in lines:
if '[截图]' in line and ('成功' in line or '✓' in line):
# 提取时间戳
time_match = re.search(r'(\d{2}:\d{2}:\d{2})', line)
if time_match:
try:
time_str = time_match.group(1)
# 转换为秒数(简化处理)
h, m, s = map(int, time_str.split(':'))
timestamp = h * 3600 + m * 60 + s
screenshot_timestamps.append(timestamp)
except Exception:
pass
if len(screenshot_timestamps) >= 2:
intervals = []
for i in range(1, len(screenshot_timestamps)):
interval = screenshot_timestamps[i] - screenshot_timestamps[i-1]
if interval > 0: # 避免负数
intervals.append(interval)
if intervals:
avg_interval = sum(intervals) / len(intervals)
min_interval = min(intervals)
print(f"截图时间间隔分析(共 {len(intervals)} 个间隔):")
print(f" 平均间隔: {avg_interval:.2f} 秒")
print(f" 最短间隔: {min_interval:.2f} 秒")
print()
if min_interval < 1.0:
print(" ✅ 发现快速连续截图(间隔 < 1秒)")
print(" 说明缓存可能生效,响应速度很快")
elif min_interval < 2.0:
print(" ⚠️ 截图间隔较长(1-2秒)")
print(" 可能是正常操作间隔,或缓存未完全生效")
else:
print(" ⚠️ 截图间隔较长(> 2秒)")
print(" 可能是正常操作间隔")
else:
print("数据不足,无法分析缓存效果")
def check_code_integration():
"""检查代码集成"""
print("\n" + "=" * 60)
print("4. 检查代码集成")
print("=" * 60)
# 检查 douyin_fudai.py
douyin_fudai_path = "douyin/core/douyin_fudai.py"
if os.path.exists(douyin_fudai_path):
with open(douyin_fudai_path, 'r', encoding='utf-8') as f:
content = f.read()
if 'ScreenshotService' in content and 'service.start' in content:
print("✅ douyin_fudai.py 已包含服务启动代码")
else:
print("❌ douyin_fudai.py 未包含服务启动代码")
else:
print(f"❌ 文件不存在: {douyin_fudai_path}")
# 检查 screenshot_operations.py
screenshot_ops_path = "operations/screenshot_operations.py"
if os.path.exists(screenshot_ops_path):
with open(screenshot_ops_path, 'r', encoding='utf-8') as f:
content = f.read()
if 'use_service' in content:
print("✅ screenshot_operations.py 已支持服务模式")
else:
print("❌ screenshot_operations.py 未支持服务模式")
else:
print(f"❌ 文件不存在: {screenshot_ops_path}")
def main():
"""主函数"""
print("\n" + "=" * 60)
print("截图优化效果检查")
print("=" * 60)
print()
# 分析最新日志
result = analyze_latest_log()
if not result:
return 1
lines, log_file = result
# 检查服务启动
service_started = check_service_startup(lines)
# 分析性能
analyze_screenshot_performance(lines, service_started)
# 检查缓存效果
check_cache_effectiveness(lines)
# 检查代码集成
check_code_integration()
# 总结
print("\n" + "=" * 60)
print("检查总结")
print("=" * 60)
if service_started:
print("✅ 服务已启动")
print(" 如果截图耗时仍然较长,可能原因:")
print(" 1. 首次截图需要等待服务启动(1.5秒)")
print(" 2. 缓存未命中,需要等待后台截图完成")
print(" 3. 某些操作强制刷新截图(force=True)")
else:
print("❌ 服务未启动")
print(" 请重新运行程序,服务会在启动时自动启动")
print(" 查看日志中是否有 '[截图服务] 已启动后台截图服务'")
print()
print("优化效果验证方法:")
print("1. 重新运行程序")
print("2. 观察首次截图后的后续截图速度")
print("3. 如果缓存命中,响应时间应该 < 0.1秒")
print("4. 运行: python tools/analyze_screenshot_logs.py")
return 0
if __name__ == '__main__':
sys.exit(main())
+297
View File
@@ -0,0 +1,297 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""检查系统配置是否适合多线程处理"""
import sys
import os
import platform
# 设置UTF-8输出
if sys.platform == 'win32':
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
def check_cpu():
"""检查CPU配置"""
print("=" * 60)
print("CPU 配置检查")
print("=" * 60)
cpu_count = os.cpu_count()
if cpu_count:
print(f"CPU核心数: {cpu_count}")
# 评估
if cpu_count >= 8:
print("✅ CPU配置: 优秀 (8核+)")
print(" 推荐线程数: 8-12")
print(" 性能提升: 60-70%")
elif cpu_count >= 4:
print("✅ CPU配置: 良好 (4-7核)")
print(" 推荐线程数: 4-6")
print(" 性能提升: 50-60%")
elif cpu_count >= 2:
print("⚠️ CPU配置: 基础 (2-3核)")
print(" 推荐线程数: 2-3")
print(" 性能提升: 30-40%")
else:
print("❌ CPU配置: 不足 (单核)")
print(" 不推荐使用多线程")
else:
print("❌ 无法检测CPU核心数")
# 获取CPU信息(Windows)
try:
import subprocess
result = subprocess.run(
['wmic', 'cpu', 'get', 'name'],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
lines = result.stdout.strip().split('\n')
if len(lines) > 1:
cpu_name = lines[1].strip()
if cpu_name:
print(f"CPU型号: {cpu_name}")
except Exception:
pass
print()
def check_memory():
"""检查内存配置"""
print("=" * 60)
print("内存配置检查")
print("=" * 60)
try:
import psutil
mem = psutil.virtual_memory()
total_gb = mem.total / (1024**3)
available_gb = mem.available / (1024**3)
used_percent = mem.percent
print(f"总内存: {total_gb:.2f} GB")
print(f"可用内存: {available_gb:.2f} GB")
print(f"已用内存: {used_percent:.1f}%")
# 评估
if total_gb >= 16:
print("✅ 内存配置: 优秀 (16GB+)")
print(" 可以支持大量并发任务")
elif total_gb >= 8:
print("✅ 内存配置: 良好 (8-15GB)")
print(" 可以流畅运行多线程处理")
elif total_gb >= 4:
print("⚠️ 内存配置: 基础 (4-7GB)")
print(" 可以运行,但可能较慢")
else:
print("❌ 内存配置: 不足 (<4GB)")
print(" 不推荐使用多线程")
# 检查当前可用内存
if available_gb < 2:
print("⚠️ 警告: 可用内存不足2GB,可能影响性能")
except ImportError:
print("⚠️ psutil未安装,无法检测内存")
print(" 安装命令: pip install psutil")
print(" 或手动检查: 任务管理器 -> 性能 -> 内存")
except Exception as e:
print(f"❌ 内存检测失败: {e}")
print()
def check_python():
"""检查Python版本"""
print("=" * 60)
print("Python 版本检查")
print("=" * 60)
version = sys.version_info
print(f"Python版本: {version.major}.{version.minor}.{version.micro}")
if version >= (3, 10):
print("✅ Python版本: 优秀 (3.10+)")
elif version >= (3, 8):
print("✅ Python版本: 良好 (3.8-3.9)")
else:
print("❌ Python版本: 过低 (<3.8)")
print(" 建议升级到 Python 3.8+")
print()
def check_system():
"""检查操作系统"""
print("=" * 60)
print("操作系统检查")
print("=" * 60)
system = platform.system()
version = platform.version()
arch = platform.machine()
print(f"操作系统: {system}")
print(f"系统版本: {version}")
print(f"架构: {arch}")
if system == 'Windows':
if '64' in arch or 'AMD64' in arch:
print("✅ 系统架构: 64位 (支持)")
else:
print("❌ 系统架构: 32位 (不支持)")
else:
print("⚠️ 非Windows系统,可能不兼容")
print()
def check_disk():
"""检查磁盘空间"""
print("=" * 60)
print("磁盘空间检查")
print("=" * 60)
try:
import shutil
total, used, free = shutil.disk_usage('.')
total_gb = total / (1024**3)
free_gb = free / (1024**3)
used_percent = (used / total) * 100
print(f"总空间: {total_gb:.2f} GB")
print(f"可用空间: {free_gb:.2f} GB")
print(f"已用空间: {used_percent:.1f}%")
if free_gb >= 10:
print("✅ 磁盘空间: 充足 (10GB+)")
elif free_gb >= 5:
print("✅ 磁盘空间: 足够 (5-9GB)")
elif free_gb >= 2:
print("⚠️ 磁盘空间: 基础 (2-4GB)")
else:
print("❌ 磁盘空间: 不足 (<2GB)")
print(" 建议清理磁盘空间")
except Exception as e:
print(f"❌ 磁盘检测失败: {e}")
print()
def get_recommendation():
"""给出综合建议"""
print("=" * 60)
print("综合评估与建议")
print("=" * 60)
try:
cpu_count = os.cpu_count() or 4
try:
import psutil
mem = psutil.virtual_memory()
total_gb = mem.total / (1024**3)
except ImportError:
total_gb = 8 # 假设8GB
# 综合评分
score = 0
recommendations = []
# CPU评分
if cpu_count >= 8:
score += 30
cpu_status = "优秀"
elif cpu_count >= 4:
score += 20
cpu_status = "良好"
elif cpu_count >= 2:
score += 10
cpu_status = "基础"
else:
cpu_status = "不足"
# 内存评分
if total_gb >= 16:
score += 30
mem_status = "优秀"
elif total_gb >= 8:
score += 20
mem_status = "良好"
elif total_gb >= 4:
score += 10
mem_status = "基础"
else:
mem_status = "不足"
# Python版本评分
if sys.version_info >= (3, 10):
score += 20
elif sys.version_info >= (3, 8):
score += 15
# 系统评分
if platform.system() == 'Windows' and ('64' in platform.machine() or 'AMD64' in platform.machine()):
score += 20
# 给出建议
print(f"综合评分: {score}/100")
print()
if score >= 80:
print("✅ 你的电脑非常适合多线程处理!")
print(" 建议:")
print(" - 使用 6-8 个线程")
print(" - 可以充分利用多核CPU")
print(" - 性能提升: 60-70%")
elif score >= 60:
print("✅ 你的电脑适合多线程处理")
print(" 建议:")
print(" - 使用 4-6 个线程")
print(" - 可以正常使用多线程")
print(" - 性能提升: 40-50%")
elif score >= 40:
print("⚠️ 你的电脑可以运行多线程,但效果有限")
print(" 建议:")
print(" - 使用 2-3 个线程")
print(" - 性能提升: 20-30%")
else:
print("❌ 你的电脑不太适合多线程处理")
print(" 建议:")
print(" - 使用单线程或2线程")
print(" - 考虑升级硬件")
print()
print(f"CPU状态: {cpu_status} ({cpu_count}核)")
print(f"内存状态: {mem_status} ({total_gb:.1f}GB)")
except Exception as e:
print(f"评估失败: {e}")
def main():
"""主函数"""
print("\n" + "=" * 60)
print("系统配置检查 - 多线程处理适配性分析")
print("=" * 60)
print()
check_system()
check_python()
check_cpu()
check_memory()
check_disk()
get_recommendation()
print()
print("=" * 60)
print("检查完成")
print("=" * 60)
if __name__ == '__main__':
main()
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
-328
View File
@@ -1,328 +0,0 @@
"""
Web 端自動化巡檢腳本
====================
用途:
- 打開 Web GUI(預設 http://127.0.0.1:8000/)
- 點擊「開始運行」
- 週期性採集:
- 日誌區域:<pre id="log">
- 實時截圖:<img id="liveShot">
- 在本地保留整個測試期間的所有截圖,並將每次截圖時的日誌文本一併保存,方便一一對應排查。
依賴:
pip install playwright
playwright install
用法示例(PowerShell)::
cd C:\\Users\\12742\\Desktop\\douyin_guaji-main
python -m tools.test_web_gui ^
--url http://127.0.0.1:8000 ^
--duration-seconds 300 ^
--interval-seconds 5 ^
--output-dir web_test_artifacts
注意:
- 本腳本只負責 Web 前端監控,不會啟動後端服務;
請先確保你的 Web GUI(例如 web_gui.py / webgui_launcher.py)已經在本機監聽 8000 埠。
- 爲了測得更全面,建議在測試前先配置好 Web GUI 的各種選項(福袋條件、定時禁搶、預約、高價值回訪等),
然後再跑本腳本。
"""
from __future__ import annotations
import argparse
import asyncio
import json
import textwrap
from dataclasses import dataclass, asdict
from datetime import datetime
from pathlib import Path
from typing import List, Optional
import shutil
from playwright.async_api import async_playwright, Page
LOG_SELECTOR = "pre#log"
SHOT_SELECTOR = "img#liveShot"
@dataclass
class SampleRecord:
index: int
timestamp: str
screenshot_path: str
log_path: str
log_tail: str
async def _click_button_if_exists(page: Page, name: str) -> bool:
"""按 aria-label/文字內容尋找對應按鈕並點擊。"""
try:
button = page.get_by_role("button", name=name)
if await button.count() > 0:
await button.first.click()
return True
except Exception:
# 測試腳本不因一次點擊失敗而中止
return False
return False
async def _ensure_started(page: Page) -> None:
"""嘗試點擊「開始運行」啟動 Web GUI 後端任務。"""
# 先嘗試點「刷新設備」,避免沒有設備時直接失敗
await _click_button_if_exists(page, "刷新设备")
await asyncio.sleep(2.0) # 增加等待時間,確保設備列表刷新完成
# 檢查是否有設備可用
try:
# 嘗試讀取日誌,看是否有設備相關信息
log_element = await page.query_selector(LOG_SELECTOR)
if log_element:
log_text = await log_element.inner_text()
if "未检测到设备" in log_text or "未发现设备" in log_text:
print("[警告] Web GUI 顯示未檢測到設備,請確認:")
print(" 1. 手機已通過 USB 連接電腦")
print(" 2. 已開啟 USB 調試並授權")
print(" 3. 在命令行運行 'adb devices' 能看到設備")
except Exception:
pass
# 點擊「開始運行」
clicked = await _click_button_if_exists(page, "开始运行")
if clicked:
print("[測試腳本] 已點擊「開始運行」按鈕")
await asyncio.sleep(3.0) # 等待後端啟動子進程
# 再次檢查日誌,確認是否真的啟動了
try:
log_element = await page.query_selector(LOG_SELECTOR)
if log_element:
log_text = await log_element.inner_text()
if "[啟動]" in log_text or "[主循環]" in log_text or "設備分辨率" in log_text:
print("[測試腳本] ✓ 掛機進程似乎已啟動(日誌中有啟動相關信息)")
elif "already running" in log_text or "已在運行" in log_text:
print("[測試腳本] ⚠ Web GUI 顯示任務已在運行中")
else:
print("[測試腳本] ⚠ 未在日誌中看到明顯的啟動信息,可能:")
print(" - 設備未選擇或未連接")
print(" - 後端啟動子進程失敗")
print(" - 請手動在瀏覽器中檢查 Web GUI 的日誌區域")
except Exception:
pass
else:
print("[測試腳本] ⚠ 未能點擊「開始運行」按鈕,可能按鈕不存在或頁面未完全加載")
async def _ensure_stopped(page: Page) -> None:
"""測試結束時,嘗試點擊「停止」按鈕。"""
await _click_button_if_exists(page, "停止")
async def run_web_test(
url: str,
duration_seconds: int,
interval_seconds: float,
output_dir: Path,
) -> List[SampleRecord]:
"""主測試邏輯。
- 打開頁面並嘗試點「開始運行」
- 在整個 duration_seconds 期間,每 interval_seconds:
- 讀取 #log 文字並寫入 .log 檔
- 對 #liveShot 做元素截圖,保存為 .png
- 記錄 index / timestamp / 檔名 / 日誌尾部(方便快速總覽)
"""
output_dir.mkdir(parents=True, exist_ok=True)
screenshots_dir = output_dir / "screenshots"
logs_dir = output_dir / "logs"
screenshots_dir.mkdir(exist_ok=True)
logs_dir.mkdir(exist_ok=True)
meta_records: List[SampleRecord] = []
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto(url)
# 等頁面穩定
await page.wait_for_timeout(2000)
# 儘量確保任務已經啟動
await _ensure_started(page)
start = datetime.utcnow()
end_time = start.timestamp() + duration_seconds
index = 0
last_log_text: Optional[str] = None
while datetime.utcnow().timestamp() < end_time:
now = datetime.utcnow()
timestamp_str = now.strftime("%Y-%m-%d_%H-%M-%S")
# 抓取日誌
log_element = await page.query_selector(LOG_SELECTOR)
log_text = ""
if log_element is not None:
try:
log_text = await log_element.inner_text()
except Exception:
log_text = ""
# 取日誌尾部幾行方便總覽
log_tail = ""
if log_text:
lines = [ln for ln in log_text.splitlines() if ln.strip()]
tail_lines = lines[-10:] if len(lines) > 10 else lines
log_tail = "\n".join(tail_lines)
# 保存完整日誌到檔案
log_filename = f"log_{index:04d}_{timestamp_str}.log"
log_path = logs_dir / log_filename
log_path.write_text(log_text, encoding="utf-8", errors="ignore")
# 抓取實時截圖元素
shot_element = await page.query_selector(SHOT_SELECTOR)
screenshot_filename = f"screenshot_{index:04d}_{timestamp_str}.png"
screenshot_path = screenshots_dir / screenshot_filename
if shot_element is not None:
try:
await shot_element.screenshot(path=str(screenshot_path))
except Exception:
# 如果元素截圖失敗,退而求其次截整頁
await page.screenshot(path=str(screenshot_path))
else:
# 找不到元素,同樣退回整頁截圖
await page.screenshot(path=str(screenshot_path))
record = SampleRecord(
index=index,
timestamp=timestamp_str,
screenshot_path=str(screenshot_path),
log_path=str(log_path),
log_tail=log_tail,
)
meta_records.append(record)
# 簡單在控制台輸出概況,幫助快速觀察測試是否卡死
has_new_log = log_text != last_log_text
last_log_text = log_text
summary_tail = textwrap.shorten(
log_tail.replace("\n", " / "), width=120, placeholder="..."
)
print(
f"[{index:04d}] {timestamp_str} "
f"new_log={has_new_log} "
f"screenshot={screenshot_filename} "
f"log_tail={summary_tail}"
)
index += 1
await asyncio.sleep(interval_seconds)
# 測試結束,嘗試點「停止」
await _ensure_stopped(page)
await browser.close()
# 把所有採樣記錄寫入 summary.json,方便後續分析
summary_path = output_dir / "summary.json"
summary_path.write_text(
json.dumps([asdict(r) for r in meta_records], ensure_ascii=False, indent=2),
encoding="utf-8",
)
print(f"\n測試完成,共生成 {len(meta_records)} 組截圖+日誌樣本,詳見:{output_dir}")
return meta_records
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="針對 Web GUI 的自動化巡檢腳本,監控 #log 與 #liveShot 並保存全部截圖。"
)
parser.add_argument(
"--url",
default="http://127.0.0.1:8000/",
help="Web GUI 的地址(預設: http://127.0.0.1:8000/)",
)
parser.add_argument(
"--duration-seconds",
type=int,
default=300,
help="整體測試時長(秒),預設 300 秒(5分鐘)",
)
parser.add_argument(
"--interval-seconds",
type=float,
default=5.0,
help="採樣間隔(秒),預設 5 秒保存一次截圖與日誌",
)
parser.add_argument(
"--output-dir",
type=str,
default="web_test_runs",
help="測試根目錄(會在其中按時間自動建立子目錄),用於保存本次測試的所有資料",
)
return parser.parse_args()
def _snapshot_context_files(run_root: Path) -> None:
"""在每次測試目錄下備份當前關鍵配置與狀態,方便之後一併打包分析。"""
project_root = Path(".").resolve()
context_dir = run_root / "context"
context_dir.mkdir(parents=True, exist_ok=True)
# 一些關鍵單檔:當前配置與入口/主流程
important_files = [
"config/config.json",
"run_cli.py",
"douyin/core/douyin_fudai.py",
"douyin/stage/douyin_stage.py",
"douyin_fudai_core.py",
"douyin_reservation.py",
"douyin_robot.py",
]
for name in important_files:
src = project_root / name
if src.exists():
shutil.copy2(src, context_dir / src.name)
# state 目錄(包括 reservations.json / high_value_rooms.json 等)
state_src = project_root / "state"
if state_src.is_dir():
state_dst = context_dir / "state"
shutil.copytree(state_src, state_dst, dirs_exist_ok=True)
def main() -> None:
args = parse_args()
root_dir = Path(args.output_dir)
# 爲每次測試建立單獨的子目錄,名稱帶時間戳,方便你直接整個資料夾打包給我分析
ts = datetime.now().strftime("run_%Y%m%d_%H%M%S")
run_root = root_dir / ts
run_root.mkdir(parents=True, exist_ok=True)
# 備份當前配置與狀態
_snapshot_context_files(run_root)
# 再在該目錄下建立 web 測試輸出
output_dir = run_root / "web_artifacts"
asyncio.run(
run_web_test(
url=args.url,
duration_seconds=args.duration_seconds,
interval_seconds=args.interval_seconds,
output_dir=output_dir,
)
)
if __name__ == "__main__":
main()
-146
View File
@@ -1,146 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
在两个指定小区域内统计白色像素比例,用于辅助判断右上角是否有关闭 X 图标。
用法示例:
python tools/test_white_regions_x.py pic/screenshot_recommend.png pic/screenshot_live.png
思路:
- 假设原始截图分辨率约为 1080x2400(宽x高),并使用与代码中像素检测相同的坐标系。
- X 图标所在的大 ROI 为 (972,147)-(1047,216)
- 你在 pick_coords 中点出的两个白色点大致为:
P1 = (999,174)
P2 = (1025,201)
- 本脚本在这两个点附近取一个小方框(默认 7x7),统计白色像素比例。
"""
import os
import sys
from typing import Tuple, List
import cv2
import numpy as np
# 修正 Windows 控制台编码问题
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
def load_image(path: str) -> np.ndarray:
"""加载图片(支持中文路径),返回 BGR 图像。"""
if not os.path.exists(path):
raise FileNotFoundError(path)
data = np.fromfile(path, dtype=np.uint8)
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
if img is None:
raise RuntimeError(f"无法读取图片: {path}")
return img
def crop_region(
img: np.ndarray, x1: int, y1: int, x2: int, y2: int
) -> np.ndarray:
h, w = img.shape[:2]
x1 = max(0, min(w - 1, x1))
x2 = max(0, min(w, x2))
y1 = max(0, min(h - 1, y1))
y2 = max(0, min(h, y2))
if x2 <= x1 or y2 <= y1:
return img[0:0, 0:0]
return img[y1:y2, x1:x2]
def count_white_pixels(region: np.ndarray, gray_threshold: int = 245, diff_threshold: int = 10) -> Tuple[int, int, float]:
"""
统计区域内“白色像素”数量。
- gray_threshold: 灰度阈值(越大越严格,默认 245)
- diff_threshold: RGB 分量差异阈值(越小越接近纯白,默认 10)
"""
if region.size == 0:
return 0, 0, 0.0
b, g, r = cv2.split(region)
gray = cv2.cvtColor(region, cv2.COLOR_BGR2GRAY)
# 灰度足够亮
bright = gray >= gray_threshold
# RGB 三通道差异不大(接近无色)
diff_rg = np.abs(r.astype(np.int16) - g.astype(np.int16)) <= diff_threshold
diff_rb = np.abs(r.astype(np.int16) - b.astype(np.int16)) <= diff_threshold
diff_gb = np.abs(g.astype(np.int16) - b.astype(np.int16)) <= diff_threshold
white_mask = bright & diff_rg & diff_rb & diff_gb
white_count = int(white_mask.sum())
total = int(region.shape[0] * region.shape[1])
ratio = white_count / total if total > 0 else 0.0
return white_count, total, ratio
def analyse_image(
path: str,
p1: Tuple[int, int],
p2: Tuple[int, int],
) -> None:
"""对单张截图进行分析并打印结果(使用两点组成的对角矩形区域)。"""
img = load_image(path)
h, w = img.shape[:2]
print("=" * 80)
print(f"图片: {path}")
print(f"尺寸: {w}x{h}")
# 如果不是接近 1080x2400,可以按宽高比例缩放坐标
base_w, base_h = 1080, 2400
scale_x = w / base_w
scale_y = h / base_h
def scaled_point(p: Tuple[int, int]) -> Tuple[int, int]:
return int(round(p[0] * scale_x)), int(round(p[1] * scale_y))
sp1 = scaled_point(p1)
sp2 = scaled_point(p2)
# 使用两点组成对角矩形区域
x1, y1 = sp1
x2, y2 = sp2
rx1, ry1 = min(x1, x2), min(y1, y2)
rx2, ry2 = max(x1, x2), max(y1, y2)
region = crop_region(img, rx1, ry1, rx2, ry2)
# 为了更接近“纯白”,在这个测试里稍微提高阈值要求
white_count, total, ratio = count_white_pixels(region, gray_threshold=250, diff_threshold=5)
print(f"矩形区域(基于原坐标): {p1} - {p2}")
print(f"实际像素区域: ({rx1},{ry1})-({rx2},{ry2}), 尺寸={region.shape[1]}x{region.shape[0]}")
print(f"纯白像素: {white_count}/{total}, 比例={ratio:.4f}")
def main(argv: List[str]) -> int:
if len(argv) < 2:
print(
"用法: python tools/test_white_regions_x.py <图片1> [图片2 ...]\n"
"建议:分别传入推荐页截图和直播间截图,对比输出的白色像素比例。"
)
return 1
# 你在 pick_coords 中点出的两个点
p1 = (999, 174)
p2 = (1025, 201)
for path in argv[1:]:
try:
analyse_image(path, p1, p2)
except Exception as e:
print(f"分析失败: {path} -> {e}")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
-166
View File
@@ -1,166 +0,0 @@
import json
import time
import urllib.request
import urllib.error
from datetime import datetime
BASE = "http://127.0.0.1:8765"
def _get(path: str, timeout: float = 5.0) -> dict:
with urllib.request.urlopen(BASE + path, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
def _post(path: str, payload: dict, timeout: float = 15.0) -> dict:
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
BASE + path,
data=data,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
def _is_click_join(line: str) -> bool:
s = line or ""
return ("点击参与抽奖" in s) or ("[参与]" in s and "动作=点击参与" in s)
def _is_attend_ok(line: str) -> bool:
s = line or ""
return (
("已经参与,等待开奖" in s)
or ("已经参与,等待看播时间凑齐开奖" in s)
or ("已参与成功(或看播中)" in s)
or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s))
)
def main() -> int:
print("[测试] Web GUI 地址:", BASE)
print("[测试] 开始时间:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
devices_resp = _get("/api/devices")
devices = devices_resp.get("devices") or []
print("[测试] ADB:", devices_resp.get("adb"))
print("[测试] 设备列表:", devices)
if not devices:
print("[测试][失败] 未发现任何 ADB 设备(请确认 adb devices 能看到设备)")
return 2
device_id = devices[0]
print("[测试] 使用设备:", device_id)
# 停止旧进程
try:
_post("/api/stop", {})
time.sleep(0.5)
except Exception:
pass
# baseline logs
last_idx = 0
try:
base_logs = _get("/api/logs?since=0")
last_idx = int(base_logs.get("next") or 0)
except Exception:
last_idx = 0
payload = {
"device_id": device_id,
"y_pianyi": 0,
"needswitch": True,
"wait_minutes": 5,
}
try:
start_resp = _post("/api/start-run", payload)
print("[测试] 启动挂机:", start_resp)
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="replace")
print("[测试][失败] 启动 HTTPError:", e.code, body)
return 3
duration_seconds = 300
print(f"[测试] 监控时长:{duration_seconds} 秒(5 分钟)")
start_ts = time.time()
key_lines: list[str] = []
saw_click_join = False
saw_attend_ok = False
abnormal_count = 0
last_stats_ts = 0.0
try:
while time.time() - start_ts < duration_seconds:
j = _get(f"/api/logs?since={last_idx}")
last_idx = int(j.get("next") or last_idx)
lines = j.get("lines") or []
for ln in lines:
if any(k in ln for k in ("[截图]", "[详情]", "[异常]", "[参与]", "[预约]", "点击打开福袋详情")):
key_lines.append(ln)
if _is_click_join(ln):
saw_click_join = True
if _is_attend_ok(ln):
saw_attend_ok = True
if "[异常]" in ln:
abnormal_count += 1
# 每 10 秒打一次 stats(更直观看是否有“参与点击/参与成功”计数)
now = time.time()
if now - last_stats_ts >= 10:
last_stats_ts = now
try:
st = _get("/api/stats")
c = st.get("counters") or {}
print(
"[测试][统计] 运行=", st.get("running"),
" 参与点击=", c.get("fudai_click_attend", 0),
" 参与成功=", c.get("fudai_attend_ok", 0),
" 打开详情=", c.get("fudai_open_detail", 0),
" 异常打开=", c.get("fudai_open_error", 0),
)
except Exception:
pass
# 已经出现“点击参与+参与成功”就提前结束(你要的是5分钟内能参与)
if saw_click_join and saw_attend_ok:
print("[测试] 已检测到参与点击 + 参与成功标志,提前结束监控。")
break
time.sleep(1)
finally:
# stop
try:
stop_resp = _post("/api/stop", {})
print("[测试] 已停止挂机:", stop_resp)
except Exception as e:
print("[测试][警告] 停止失败:", e)
print("\n[测试] ===== 结果汇总 =====")
print("- 5分钟内是否出现【点击参与】:", "是" if saw_click_join else "否")
print("- 5分钟内是否出现【参与成功/已参与】:", "是" if saw_attend_ok else "否")
print("- [异常] 行计数:", abnormal_count)
print("\n[测试] ===== 关键日志(最近 120 行) =====")
for ln in key_lines[-120:]:
print(ln)
if not saw_click_join:
print("\n[测试][判定] 5分钟内没有看到‘点击参与’相关日志:可能存在问题(没打开到福袋详情/识别失败/策略跳过/禁抢时段等)。")
return 10
if saw_click_join and (not saw_attend_ok):
print("\n[测试][判定] 看到‘点击参与’,但没看到‘已参与/看播中’:可能按钮点击后未生效或被门槛/弹窗打断。")
return 11
print("\n[测试][通过] 5分钟内参与链路有证据日志。")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-136
View File
@@ -1,136 +0,0 @@
import json
import time
import urllib.error
import urllib.request
from typing import Optional
BASE = "http://127.0.0.1:8765"
def _get(path: str, timeout: float = 5.0) -> dict:
with urllib.request.urlopen(BASE + path, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
def _post(path: str, payload: dict, timeout: float = 10.0) -> dict:
data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
BASE + path,
data=data,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
def main() -> int:
devices_resp = _get("/api/devices")
devices = devices_resp.get("devices") or []
print("[smoke] devices:", devices_resp)
if not devices:
print("[smoke] ERROR: no adb devices")
return 2
device_id = devices[0]
payload = {
"device_id": device_id,
"y_pianyi": 0,
"needswitch": True,
"wait_minutes": 5,
}
# best-effort: stop any existing run to avoid mixed logs / 409
try:
_post("/api/stop", {})
time.sleep(0.5)
except Exception:
pass
# baseline logs (avoid old history)
try:
base_logs = _get("/api/logs?since=0")
last_idx = int(base_logs.get("next") or 0)
except Exception:
last_idx = 0
try:
start_resp = _post("/api/start-run", payload)
print("[smoke] start:", start_resp)
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="replace")
print("[smoke] start HTTPError:", e.code, body)
return 3
# poll logs
start_ts = time.time()
hits: list[str] = []
all_lines: list[str] = []
# 轮询最多 240 秒;命中首次“[异常] 时间/价值异常仍未恢复”后再额外等待一小段时间,
# 尽量抓到 reopen 识别结果或“持续异常”最终分支。
post_abnormal_grace_seconds = 20
abnormal_marker_ts: Optional[float] = None
while time.time() - start_ts < 240:
j = _get(f"/api/logs?since={last_idx}")
last_idx = int(j.get("next") or last_idx)
lines = j.get("lines") or []
if lines:
all_lines.extend(lines)
for ln in lines:
if any(k in ln for k in ("[截图]", "[详情]", "[异常]")):
hits.append(ln)
if abnormal_marker_ts is None and any("[异常] 时间/价值异常仍未恢复" in x for x in hits):
abnormal_marker_ts = time.time()
if any("[异常] 时间/价值持续异常" in x for x in hits):
break
if any("[详情] reopen" in x for x in hits):
break
if abnormal_marker_ts is not None and (time.time() - abnormal_marker_ts) >= post_abnormal_grace_seconds:
break
time.sleep(1)
# stop
try:
stop_resp = _post("/api/stop", {})
print("[smoke] stop:", stop_resp)
except Exception as e:
print("[smoke] stop ERROR:", e)
print("\n[smoke] ==== KEY LINES ([截图]/[详情]/[异常]) tail 80 ====")
for ln in hits[-80:]:
print(ln)
# simple verdict
has_shot = any("[截图]" in x for x in hits)
has_detail = any("[详情]" in x for x in hits)
has_abnormal = any("[异常]" in x for x in hits)
saw_first_abnormal = any(("[详情] first" in x and "异常=True" in x) for x in hits)
saw_retry1 = any("[详情] retry1" in x for x in hits)
saw_reopen = any("[详情] reopen" in x for x in hits)
saw_normal = any(("[详情]" in x and "异常=False" in x) for x in hits)
print("\n[smoke] verdict:")
print("- saw [截图]:", has_shot)
print("- saw [详情]:", has_detail)
print("- saw [异常]:", has_abnormal)
print("- saw first abnormal (first):", saw_first_abnormal)
print("- saw retry1:", saw_retry1)
print("- saw reopen:", saw_reopen)
print("- saw any normal detail:", saw_normal)
if not has_shot:
print("[smoke] NOTE: 未看到[截图],通常表示子进程未真正跑起来或日志未回流")
if has_shot and (not has_detail):
print("[smoke] NOTE: 已看到[截图]但未看到[详情],可能还没打开到福袋详情,或 OCR 初始化/识别较慢")
# also show last 30 lines for context
print("\n[smoke] ==== LAST 50 LOG LINES ====")
for ln in all_lines[-50:]:
print(ln)
return 0
if __name__ == "__main__":
raise SystemExit(main())
View File
Whitespace-only changes.