87 lines
2.5 KiB
Python
Executable File
87 lines
2.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
retry_executor.py — 通用重试执行器
|
|
用法: python3 retry_executor.py <script_path> [max_retries] [delay_seconds]
|
|
|
|
示例:
|
|
python3 retry_executor.py distill-model-watchdog.py 3 5
|
|
python3 retry_executor.py stock_dual_scan.sh 2 10
|
|
"""
|
|
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import os
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("用法: python3 retry_executor.py <script_path> [max_retries] [delay_seconds]")
|
|
sys.exit(1)
|
|
|
|
script = sys.argv[1]
|
|
max_retries = int(sys.argv[2]) if len(sys.argv) > 2 else 3
|
|
delay = int(sys.argv[3]) if len(sys.argv) > 3 else 5
|
|
|
|
# 检查脚本是否存在
|
|
if not os.path.exists(script):
|
|
# 尝试在scripts目录查找
|
|
scripts_dir = os.path.expanduser("~/.hermes/scripts")
|
|
script_path = os.path.join(scripts_dir, script)
|
|
if os.path.exists(script_path):
|
|
script = script_path
|
|
else:
|
|
print(f"错误: 脚本不存在: {script}")
|
|
sys.exit(1)
|
|
|
|
# 确定执行方式
|
|
if script.endswith('.py'):
|
|
cmd = [sys.executable, script]
|
|
elif script.endswith('.sh'):
|
|
cmd = ['bash', script]
|
|
else:
|
|
cmd = [script]
|
|
|
|
last_output = ""
|
|
last_exit_code = 1
|
|
|
|
for attempt in range(1, max_retries + 1):
|
|
print(f"尝试 {attempt}/{max_retries}: {os.path.basename(script)}")
|
|
|
|
try:
|
|
result = subprocess.run(
|
|
cmd,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=300 # 5分钟超时
|
|
)
|
|
|
|
last_output = result.stdout + result.stderr
|
|
last_exit_code = result.returncode
|
|
|
|
if result.returncode == 0:
|
|
print(last_output)
|
|
sys.exit(0)
|
|
|
|
print(f"失败 (退出码: {result.returncode})")
|
|
if result.stderr:
|
|
print(f"错误: {result.stderr[:200]}")
|
|
|
|
except subprocess.TimeoutExpired:
|
|
print(f"超时 (5分钟)")
|
|
last_exit_code = 124
|
|
except Exception as e:
|
|
print(f"异常: {e}")
|
|
last_exit_code = 1
|
|
|
|
if attempt < max_retries:
|
|
print(f"等待 {delay}s 后重试...")
|
|
time.sleep(delay)
|
|
|
|
print(f"\n所有 {max_retries} 次重试失败")
|
|
if last_output:
|
|
print(f"最后输出:\n{last_output[:500]}")
|
|
sys.exit(last_exit_code)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|