901 字
5 分钟
执行影刀应用卡死不报错,重启应用方案
本文同步自影刀社区 RPA 板块(文章),作者 【耐家军】DC:原文链接
效果展示
痛点:处理数据多了,或者程序运行时间过长往往卡在某个指令长时间不运行,关闭重新运行又可以跑,出错还可以解决,卡死束手无策
思路:
并发子流程判断卡死指令超时时间触发全程监督,先使用运行bat延迟n启动应用,通过快捷键ctrl+alt+q关闭超时程序
bat代码
@echo off:: 延迟5秒(禁止跳过,静默)timeout /t 5 /nobreak >nul:: 启动程序start "" "E:\ShadowBot\ShadowBot.exe" "shadowbot:Run?robot-uuid=d0fe7792-9fe8-46c9-b283-0bb0bb23fa12"执行指令应用参考通过UUID一键启动影刀指定应用(社区版可用)
执行bat脚本参考影刀如何调用外部Python脚本
py代码
import xbotfrom xbot import print, sleepfrom . import packagefrom .package import variables as glvimport timeimport uiautomation as autoimport win32guiimport sysimport xbot_visual
class RobotRunnerViewMonitor: def __init__(self): self.window_title = "RobotRunnerView" self.target_hwnd = None self.previous_text = "" self.last_exec_instruction_time = None # 上一条执行指令的时间戳 self.exec_instruction_count = 0 # 执行指令计数 self.timeout_threshold = 5 # 超时阈值(秒) self.is_timeout = False # 超时标记
def find_robot_runner_view(self): """查找目标窗口句柄""" hwnd = win32gui.FindWindow(None, self.window_title) return hwnd if hwnd else None
def wait_for_window(self, timeout=600): """等待目标窗口出现""" start_time = time.time() try: while time.time() - start_time < timeout: # 等待窗口时检测超时 if self.last_exec_instruction_time is not None: elapsed_since_last_exec = time.time() - self.last_exec_instruction_time if elapsed_since_last_exec > self.timeout_threshold: # 超时输出:开始时间(超时) 间隔时间 last_time_str = time.strftime('%H:%M:%S', time.localtime(self.last_exec_instruction_time)) print(f"{last_time_str}(超时) {elapsed_since_last_exec:.2f}") self.is_timeout = True return False
hwnd = self.find_robot_runner_view() if hwnd: self.target_hwnd = hwnd return True sleep(0.5) except KeyboardInterrupt: return False return False
def get_window_content(self): """获取窗口文本内容""" if not self.target_hwnd: return ""
try: window = auto.ControlFromHandle(self.target_hwnd) if not window or not window.Exists(): return ""
content = [] children = window.GetChildren() if children: for child in children: text = "" if hasattr(child, 'Text') and child.Text: text = str(child.Text).strip() elif hasattr(child, 'Name') and child.Name: text = str(child.Name).strip() elif hasattr(child, 'Value') and child.Value: text = str(child.Value).strip()
if text: content.append(text)
return "\n".join(content)
except Exception as e: return ""
def monitor_window(self): """核心监控逻辑""" # 等待窗口出现 if not self.wait_for_window(): if self.is_timeout: return return
# 初始化窗口内容 self.previous_text = self.get_window_content()
try: while True: # 实时检测超时(超过5秒终止) if self.last_exec_instruction_time is not None: elapsed_since_last_exec = time.time() - self.last_exec_instruction_time if elapsed_since_last_exec > self.timeout_threshold: # 输出超时信息:上一条执行时间(超时) 超时时长 last_time_str = time.strftime('%H:%M:%S', time.localtime(self.last_exec_instruction_time)) print(f"{last_time_str}(超时) {elapsed_since_last_exec:.2f}") xbot_visual.system.run_or_open(application_path="C:\\Users\\林夕呀\\Desktop\\yc.bat", command_line_arguments=None, working_folder=None, after_application_launch="continue", is_waitexit_not_more_than=False, timeout_for_exit="10", is_waithwnd_not_more_than=False, timeout_for_hwnd="3", start_as_admin=False, window_style="normal") xbot.win32.send_keys(keys="^!{q}", hardware_driver_input=False, force_ime_eng=False, contains_hotkey=True, send_key_delay="50", delay_after="1") self.is_timeout = True break
# 检查窗口是否关闭 if not win32gui.IsWindow(self.target_hwnd): if self.wait_for_window(timeout=300): self.previous_text = self.get_window_content() continue else: if self.is_timeout: break break
try: # 获取最新窗口内容 window = auto.ControlFromHandle(self.target_hwnd) if not window or not window.Exists(): sleep(0.5) continue
current_content = self.get_window_content()
# 检测内容变化 if current_content != self.previous_text: current_timestamp = time.time() # 当前指令的时间戳 current_time_str = time.strftime('%H:%M:%S', time.localtime(current_timestamp)) # 格式化时间
# 检测新增内容是否包含"执行" old_lines = self.previous_text.split('\n') new_lines = current_content.split('\n') has_exec_keyword = False
for new_line in new_lines: line_stripped = new_line.strip() if line_stripped and new_line not in old_lines and "执行" in line_stripped: has_exec_keyword = True
# 仅处理含"执行"的指令 if has_exec_keyword: self.exec_instruction_count += 1 interval = 0.0
# 计算与上一条执行指令的间隔 if self.last_exec_instruction_time is not None: interval = current_timestamp - self.last_exec_instruction_time # 输出格式:当前执行开始时间 间隔时间 print(f"{current_time_str} {interval:.2f}") else: # 第一条执行指令,间隔为0 print(f"{current_time_str} 0.00")
# 更新上一条执行指令的时间戳 self.last_exec_instruction_time = current_timestamp
# 更新历史内容 self.previous_text = current_content
except Exception: sleep(0.5) continue
# 控制监控频率 sleep(0.5)
except KeyboardInterrupt: pass
def main(args): """主函数""" monitor = RobotRunnerViewMonitor() monitor.monitor_window()关键py代码
"""运行bat脚本"""xbot_visual.system.run_or_open(application_path="C:\\Users\\林夕呀\\Desktop\\yc.bat", command_line_arguments=None, working_folder=None, after_application_launch="continue", is_waitexit_not_more_than=False, timeout_for_exit="10", is_waithwnd_not_more_than=False, timeout_for_hwnd="3", start_as_admin=False, window_style="normal")"""关闭当前应用"""xbot.win32.send_keys(keys="^!{q}", hardware_driver_input=False, force_ime_eng=False, contains_hotkey=True, send_key_delay="50", delay_after="1")流程参考
📦 影刀指令文件: