manage.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 新闻爬虫容器管理工具 - supercronic
  5. """
  6. import os
  7. import sys
  8. import subprocess
  9. import time
  10. import signal
  11. from pathlib import Path
  12. # Web 服务器配置
  13. WEBSERVER_PORT = int(os.environ.get("WEBSERVER_PORT", "8080"))
  14. WEBSERVER_DIR = "/app/output"
  15. WEBSERVER_PID_FILE = "/tmp/webserver.pid"
  16. def run_command(cmd, shell=True, capture_output=True):
  17. """执行系统命令"""
  18. try:
  19. result = subprocess.run(
  20. cmd, shell=shell, capture_output=capture_output, text=True
  21. )
  22. return result.returncode == 0, result.stdout, result.stderr
  23. except Exception as e:
  24. return False, "", str(e)
  25. def manual_run():
  26. """手动执行一次爬虫"""
  27. print("🔄 手动执行爬虫...")
  28. try:
  29. result = subprocess.run(
  30. ["python", "-m", "trendradar"], cwd="/app", capture_output=False, text=True
  31. )
  32. if result.returncode == 0:
  33. print("✅ 执行完成")
  34. else:
  35. print(f"❌ 执行失败,退出码: {result.returncode}")
  36. except Exception as e:
  37. print(f"❌ 执行出错: {e}")
  38. def parse_cron_schedule(cron_expr):
  39. """解析cron表达式并返回人类可读的描述"""
  40. if not cron_expr or cron_expr == "未设置":
  41. return "未设置"
  42. try:
  43. parts = cron_expr.strip().split()
  44. if len(parts) != 5:
  45. return f"原始表达式: {cron_expr}"
  46. minute, hour, day, month, weekday = parts
  47. # 分析分钟
  48. if minute == "*":
  49. minute_desc = "每分钟"
  50. elif minute.startswith("*/"):
  51. interval = minute[2:]
  52. minute_desc = f"每{interval}分钟"
  53. elif "," in minute:
  54. minute_desc = f"在第{minute}分钟"
  55. else:
  56. minute_desc = f"在第{minute}分钟"
  57. # 分析小时
  58. if hour == "*":
  59. hour_desc = "每小时"
  60. elif hour.startswith("*/"):
  61. interval = hour[2:]
  62. hour_desc = f"每{interval}小时"
  63. elif "," in hour:
  64. hour_desc = f"在{hour}点"
  65. else:
  66. hour_desc = f"在{hour}点"
  67. # 分析日期
  68. if day == "*":
  69. day_desc = "每天"
  70. elif day.startswith("*/"):
  71. interval = day[2:]
  72. day_desc = f"每{interval}天"
  73. else:
  74. day_desc = f"每月{day}号"
  75. # 分析月份
  76. if month == "*":
  77. month_desc = "每月"
  78. else:
  79. month_desc = f"在{month}月"
  80. # 分析星期
  81. weekday_names = {
  82. "0": "周日", "1": "周一", "2": "周二", "3": "周三",
  83. "4": "周四", "5": "周五", "6": "周六", "7": "周日"
  84. }
  85. if weekday == "*":
  86. weekday_desc = ""
  87. else:
  88. weekday_desc = f"在{weekday_names.get(weekday, weekday)}"
  89. # 组合描述
  90. if minute.startswith("*/") and hour == "*" and day == "*" and month == "*" and weekday == "*":
  91. # 简单的间隔模式,如 */30 * * * *
  92. return f"每{minute[2:]}分钟执行一次"
  93. elif hour != "*" and minute != "*" and day == "*" and month == "*" and weekday == "*":
  94. # 每天特定时间,如 0 9 * * *
  95. return f"每天{hour}:{minute.zfill(2)}执行"
  96. elif weekday != "*" and day == "*":
  97. # 每周特定时间
  98. return f"{weekday_desc}{hour}:{minute.zfill(2)}执行"
  99. else:
  100. # 复杂模式,显示详细信息
  101. desc_parts = [part for part in [month_desc, day_desc, weekday_desc, hour_desc, minute_desc] if part and part != "每月" and part != "每天" and part != "每小时"]
  102. if desc_parts:
  103. return " ".join(desc_parts) + "执行"
  104. else:
  105. return f"复杂表达式: {cron_expr}"
  106. except Exception as e:
  107. return f"解析失败: {cron_expr}"
  108. def show_status():
  109. """显示容器状态"""
  110. print("📊 容器状态:")
  111. # 检查 PID 1 状态
  112. supercronic_is_pid1 = False
  113. pid1_cmdline = ""
  114. try:
  115. with open('/proc/1/cmdline', 'r') as f:
  116. pid1_cmdline = f.read().replace('\x00', ' ').strip()
  117. print(f" 🔍 PID 1 进程: {pid1_cmdline}")
  118. if "supercronic" in pid1_cmdline.lower():
  119. print(" ✅ supercronic 正确运行为 PID 1")
  120. supercronic_is_pid1 = True
  121. else:
  122. print(" ❌ PID 1 不是 supercronic")
  123. print(f" 📋 实际的 PID 1: {pid1_cmdline}")
  124. except Exception as e:
  125. print(f" ❌ 无法读取 PID 1 信息: {e}")
  126. # 检查环境变量
  127. cron_schedule = os.environ.get("CRON_SCHEDULE", "未设置")
  128. run_mode = os.environ.get("RUN_MODE", "未设置")
  129. immediate_run = os.environ.get("IMMEDIATE_RUN", "未设置")
  130. print(f" ⚙️ 运行配置:")
  131. print(f" CRON_SCHEDULE: {cron_schedule}")
  132. # 解析并显示cron表达式的含义
  133. cron_description = parse_cron_schedule(cron_schedule)
  134. print(f" ⏰ 执行频率: {cron_description}")
  135. print(f" RUN_MODE: {run_mode}")
  136. print(f" IMMEDIATE_RUN: {immediate_run}")
  137. # 检查配置文件
  138. config_files = ["/app/config/config.yaml", "/app/config/frequency_words.txt"]
  139. print(" 📁 配置文件:")
  140. for file_path in config_files:
  141. if Path(file_path).exists():
  142. print(f" ✅ {Path(file_path).name}")
  143. else:
  144. print(f" ❌ {Path(file_path).name} 缺失")
  145. # 检查关键文件
  146. key_files = [
  147. ("/usr/local/bin/supercronic-linux-amd64", "supercronic二进制文件"),
  148. ("/usr/local/bin/supercronic", "supercronic软链接"),
  149. ("/tmp/crontab", "crontab文件"),
  150. ("/entrypoint.sh", "启动脚本")
  151. ]
  152. print(" 📂 关键文件检查:")
  153. for file_path, description in key_files:
  154. if Path(file_path).exists():
  155. print(f" ✅ {description}: 存在")
  156. # 对于crontab文件,显示内容
  157. if file_path == "/tmp/crontab":
  158. try:
  159. with open(file_path, 'r') as f:
  160. crontab_content = f.read().strip()
  161. print(f" 内容: {crontab_content}")
  162. except:
  163. pass
  164. else:
  165. print(f" ❌ {description}: 不存在")
  166. # 检查容器运行时间
  167. print(" ⏱️ 容器时间信息:")
  168. try:
  169. # 检查 PID 1 的启动时间
  170. with open('/proc/1/stat', 'r') as f:
  171. stat_content = f.read().strip().split()
  172. if len(stat_content) >= 22:
  173. # starttime 是第22个字段(索引21)
  174. starttime_ticks = int(stat_content[21])
  175. # 读取系统启动时间
  176. with open('/proc/stat', 'r') as stat_f:
  177. for line in stat_f:
  178. if line.startswith('btime'):
  179. boot_time = int(line.split()[1])
  180. break
  181. else:
  182. boot_time = 0
  183. # 读取系统时钟频率
  184. clock_ticks = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
  185. if boot_time > 0:
  186. pid1_start_time = boot_time + (starttime_ticks / clock_ticks)
  187. current_time = time.time()
  188. uptime_seconds = int(current_time - pid1_start_time)
  189. uptime_minutes = uptime_seconds // 60
  190. uptime_hours = uptime_minutes // 60
  191. if uptime_hours > 0:
  192. print(f" PID 1 运行时间: {uptime_hours} 小时 {uptime_minutes % 60} 分钟")
  193. else:
  194. print(f" PID 1 运行时间: {uptime_minutes} 分钟 ({uptime_seconds} 秒)")
  195. else:
  196. print(f" PID 1 运行时间: 无法精确计算")
  197. else:
  198. print(" ❌ 无法解析 PID 1 统计信息")
  199. except Exception as e:
  200. print(f" ❌ 时间检查失败: {e}")
  201. # 状态总结和建议
  202. print(" 📊 状态总结:")
  203. if supercronic_is_pid1:
  204. print(" ✅ supercronic 正确运行为 PID 1")
  205. print(" ✅ 定时任务应该正常工作")
  206. # 显示当前的调度信息
  207. if cron_schedule != "未设置":
  208. print(f" ⏰ 当前调度: {cron_description}")
  209. # 提供一些常见的调度建议
  210. if "分钟" in cron_description and "每30分钟" not in cron_description and "每60分钟" not in cron_description:
  211. print(" 💡 频繁执行模式,适合实时监控")
  212. elif "小时" in cron_description:
  213. print(" 💡 按小时执行模式,适合定期汇总")
  214. elif "天" in cron_description:
  215. print(" 💡 每日执行模式,适合日报生成")
  216. print(" 💡 如果定时任务不执行,检查:")
  217. print(" • crontab 格式是否正确")
  218. print(" • 时区设置是否正确")
  219. print(" • 应用程序是否有错误")
  220. else:
  221. print(" ❌ supercronic 状态异常")
  222. if pid1_cmdline:
  223. print(f" 📋 当前 PID 1: {pid1_cmdline}")
  224. print(" 💡 建议操作:")
  225. print(" • 重启容器: docker restart trendradar")
  226. print(" • 检查容器日志: docker logs trendradar")
  227. # 显示日志检查建议
  228. print(" 📋 运行状态检查:")
  229. print(" • 查看完整容器日志: docker logs trendradar")
  230. print(" • 查看实时日志: docker logs -f trendradar")
  231. print(" • 手动执行测试: python manage.py run")
  232. print(" • 重启容器服务: docker restart trendradar")
  233. def show_config():
  234. """显示当前配置"""
  235. print("⚙️ 当前配置:")
  236. env_vars = [
  237. "CRON_SCHEDULE",
  238. "RUN_MODE",
  239. "IMMEDIATE_RUN",
  240. "FEISHU_WEBHOOK_URL",
  241. "DINGTALK_WEBHOOK_URL",
  242. "WEWORK_WEBHOOK_URL",
  243. "TELEGRAM_BOT_TOKEN",
  244. "TELEGRAM_CHAT_ID",
  245. "CONFIG_PATH",
  246. "FREQUENCY_WORDS_PATH",
  247. # 存储配置
  248. "STORAGE_BACKEND",
  249. "LOCAL_RETENTION_DAYS",
  250. "REMOTE_RETENTION_DAYS",
  251. "STORAGE_TXT_ENABLED",
  252. "STORAGE_HTML_ENABLED",
  253. "S3_BUCKET_NAME",
  254. "S3_ACCESS_KEY_ID",
  255. "S3_ENDPOINT_URL",
  256. "S3_REGION",
  257. "PULL_ENABLED",
  258. "PULL_DAYS",
  259. ]
  260. for var in env_vars:
  261. value = os.environ.get(var, "未设置")
  262. # 隐藏敏感信息
  263. if any(sensitive in var for sensitive in ["WEBHOOK", "TOKEN", "KEY", "SECRET"]):
  264. if value and value != "未设置":
  265. masked_value = value[:10] + "***" if len(value) > 10 else "***"
  266. print(f" {var}: {masked_value}")
  267. else:
  268. print(f" {var}: {value}")
  269. else:
  270. print(f" {var}: {value}")
  271. crontab_file = "/tmp/crontab"
  272. if Path(crontab_file).exists():
  273. print(" 📅 Crontab内容:")
  274. try:
  275. with open(crontab_file, "r") as f:
  276. content = f.read().strip()
  277. print(f" {content}")
  278. except Exception as e:
  279. print(f" 读取失败: {e}")
  280. else:
  281. print(" 📅 Crontab文件不存在")
  282. def show_files():
  283. """显示输出文件"""
  284. print("📁 输出文件:")
  285. output_dir = Path("/app/output")
  286. if not output_dir.exists():
  287. print(" 📭 输出目录不存在")
  288. return
  289. # 新结构:扁平化目录
  290. # - output/news/*.db
  291. # - output/rss/*.db
  292. # - output/txt/{date}/*.txt
  293. # - output/html/{date}/*.html
  294. # 检查 news 数据库
  295. news_dir = output_dir / "news"
  296. if news_dir.exists():
  297. db_files = sorted(news_dir.glob("*.db"), key=lambda x: x.name, reverse=True)
  298. if db_files:
  299. print(f" 💾 热榜数据库 (news/): {len(db_files)} 个")
  300. for db_file in db_files[:5]:
  301. mtime = time.ctime(db_file.stat().st_mtime)
  302. size_kb = db_file.stat().st_size // 1024
  303. print(f" 📀 {db_file.name} ({size_kb}KB, {mtime.split()[3][:5]})")
  304. if len(db_files) > 5:
  305. print(f" ... 还有 {len(db_files) - 5} 个")
  306. # 检查 RSS 数据库
  307. rss_dir = output_dir / "rss"
  308. if rss_dir.exists():
  309. db_files = sorted(rss_dir.glob("*.db"), key=lambda x: x.name, reverse=True)
  310. if db_files:
  311. print(f" 📰 RSS 数据库 (rss/): {len(db_files)} 个")
  312. for db_file in db_files[:5]:
  313. mtime = time.ctime(db_file.stat().st_mtime)
  314. size_kb = db_file.stat().st_size // 1024
  315. print(f" 📀 {db_file.name} ({size_kb}KB, {mtime.split()[3][:5]})")
  316. if len(db_files) > 5:
  317. print(f" ... 还有 {len(db_files) - 5} 个")
  318. # 检查 TXT 快照目录
  319. txt_dir = output_dir / "txt"
  320. if txt_dir.exists():
  321. date_dirs = sorted([d for d in txt_dir.iterdir() if d.is_dir()], reverse=True)
  322. if date_dirs:
  323. print(f" 📄 TXT 快照 (txt/): {len(date_dirs)} 天")
  324. for date_dir in date_dirs[:3]:
  325. txt_files = list(date_dir.glob("*.txt"))
  326. if txt_files:
  327. recent = sorted(txt_files, key=lambda x: x.stat().st_mtime, reverse=True)[0]
  328. mtime = time.ctime(recent.stat().st_mtime)
  329. print(f" 📅 {date_dir.name}: {len(txt_files)} 个文件 (最新: {mtime.split()[3][:5]})")
  330. # 检查 HTML 报告目录
  331. html_dir = output_dir / "html"
  332. if html_dir.exists():
  333. date_dirs = sorted([d for d in html_dir.iterdir() if d.is_dir()], reverse=True)
  334. if date_dirs:
  335. print(f" 🌐 HTML 报告 (html/): {len(date_dirs)} 天")
  336. for date_dir in date_dirs[:3]:
  337. html_files = list(date_dir.glob("*.html"))
  338. if html_files:
  339. recent = sorted(html_files, key=lambda x: x.stat().st_mtime, reverse=True)[0]
  340. mtime = time.ctime(recent.stat().st_mtime)
  341. print(f" 📅 {date_dir.name}: {len(html_files)} 个文件 (最新: {mtime.split()[3][:5]})")
  342. def show_logs():
  343. """显示实时日志"""
  344. print("📋 实时日志 (按 Ctrl+C 退出):")
  345. print("💡 提示: 这将显示 PID 1 进程的输出")
  346. try:
  347. # 尝试多种方法查看日志
  348. log_files = [
  349. "/proc/1/fd/1", # PID 1 的标准输出
  350. "/proc/1/fd/2", # PID 1 的标准错误
  351. ]
  352. for log_file in log_files:
  353. if Path(log_file).exists():
  354. print(f"📄 尝试读取: {log_file}")
  355. subprocess.run(["tail", "-f", log_file], check=True)
  356. break
  357. else:
  358. print("📋 无法找到标准日志文件,建议使用: docker logs trendradar")
  359. except KeyboardInterrupt:
  360. print("\n👋 退出日志查看")
  361. except Exception as e:
  362. print(f"❌ 查看日志失败: {e}")
  363. print("💡 建议使用: docker logs trendradar")
  364. def restart_supercronic():
  365. """重启supercronic进程"""
  366. print("🔄 重启supercronic...")
  367. print("⚠️ 注意: supercronic 是 PID 1,无法直接重启")
  368. # 检查当前 PID 1
  369. try:
  370. with open('/proc/1/cmdline', 'r') as f:
  371. pid1_cmdline = f.read().replace('\x00', ' ').strip()
  372. print(f" 🔍 当前 PID 1: {pid1_cmdline}")
  373. if "supercronic" in pid1_cmdline.lower():
  374. print(" ✅ PID 1 是 supercronic")
  375. print(" 💡 要重启 supercronic,需要重启整个容器:")
  376. print(" docker restart trendradar")
  377. else:
  378. print(" ❌ PID 1 不是 supercronic,这是异常状态")
  379. print(" 💡 建议重启容器以修复问题:")
  380. print(" docker restart trendradar")
  381. except Exception as e:
  382. print(f" ❌ 无法检查 PID 1: {e}")
  383. print(" 💡 建议重启容器: docker restart trendradar")
  384. def start_webserver():
  385. """启动 Web 服务器托管 output 目录"""
  386. print(f"🌐 启动 Web 服务器 (端口: {WEBSERVER_PORT})...")
  387. print(f" 🔒 安全提示:仅提供静态文件访问,限制在 {WEBSERVER_DIR} 目录")
  388. # 检查是否已经运行
  389. if Path(WEBSERVER_PID_FILE).exists():
  390. try:
  391. with open(WEBSERVER_PID_FILE, 'r') as f:
  392. old_pid = int(f.read().strip())
  393. try:
  394. os.kill(old_pid, 0) # 检查进程是否存在
  395. print(f" ⚠️ Web 服务器已在运行 (PID: {old_pid})")
  396. print(f" 💡 访问: http://localhost:{WEBSERVER_PORT}")
  397. print(" 💡 停止服务: python manage.py stop_webserver")
  398. return
  399. except OSError:
  400. # 进程不存在,删除旧的 PID 文件
  401. os.remove(WEBSERVER_PID_FILE)
  402. except Exception as e:
  403. print(f" ⚠️ 清理旧的 PID 文件: {e}")
  404. try:
  405. os.remove(WEBSERVER_PID_FILE)
  406. except:
  407. pass
  408. # 检查目录是否存在
  409. if not Path(WEBSERVER_DIR).exists():
  410. print(f" ❌ 目录不存在: {WEBSERVER_DIR}")
  411. return
  412. try:
  413. # 启动 HTTP 服务器
  414. # 使用 --bind 绑定到 0.0.0.0 使容器内部可访问
  415. # 工作目录限制在 WEBSERVER_DIR,防止访问其他目录
  416. process = subprocess.Popen(
  417. [sys.executable, '-m', 'http.server', str(WEBSERVER_PORT), '--bind', '0.0.0.0'],
  418. cwd=WEBSERVER_DIR,
  419. stdout=subprocess.DEVNULL,
  420. stderr=subprocess.DEVNULL,
  421. start_new_session=True
  422. )
  423. # 等待一下确保服务器启动
  424. time.sleep(1)
  425. # 检查进程是否还在运行
  426. if process.poll() is None:
  427. # 保存 PID
  428. with open(WEBSERVER_PID_FILE, 'w') as f:
  429. f.write(str(process.pid))
  430. print(f" ✅ Web 服务器已启动 (PID: {process.pid})")
  431. print(f" 📁 服务目录: {WEBSERVER_DIR} (只读,仅静态文件)")
  432. print(f" 🌐 访问地址: http://localhost:{WEBSERVER_PORT}")
  433. print(f" 📄 首页: http://localhost:{WEBSERVER_PORT}/index.html")
  434. print(" 💡 停止服务: python manage.py stop_webserver")
  435. else:
  436. print(f" ❌ Web 服务器启动失败")
  437. except Exception as e:
  438. print(f" ❌ 启动失败: {e}")
  439. def stop_webserver():
  440. """停止 Web 服务器"""
  441. print("🛑 停止 Web 服务器...")
  442. if not Path(WEBSERVER_PID_FILE).exists():
  443. print(" ℹ️ Web 服务器未运行")
  444. return
  445. try:
  446. with open(WEBSERVER_PID_FILE, 'r') as f:
  447. pid = int(f.read().strip())
  448. try:
  449. # 尝试终止进程
  450. os.kill(pid, signal.SIGTERM)
  451. time.sleep(0.5)
  452. # 检查进程是否已终止
  453. try:
  454. os.kill(pid, 0)
  455. # 进程还在,强制杀死
  456. os.kill(pid, signal.SIGKILL)
  457. print(f" ⚠️ 强制停止 Web 服务器 (PID: {pid})")
  458. except OSError:
  459. print(f" ✅ Web 服务器已停止 (PID: {pid})")
  460. except OSError as e:
  461. if e.errno == 3: # No such process
  462. print(f" ℹ️ 进程已不存在 (PID: {pid})")
  463. else:
  464. raise
  465. # 删除 PID 文件
  466. os.remove(WEBSERVER_PID_FILE)
  467. except Exception as e:
  468. print(f" ❌ 停止失败: {e}")
  469. # 尝试清理 PID 文件
  470. try:
  471. os.remove(WEBSERVER_PID_FILE)
  472. except:
  473. pass
  474. def webserver_status():
  475. """查看 Web 服务器状态"""
  476. print("🌐 Web 服务器状态:")
  477. if not Path(WEBSERVER_PID_FILE).exists():
  478. print(" ⭕ 未运行")
  479. print(f" 💡 启动服务: python manage.py start_webserver")
  480. return
  481. try:
  482. with open(WEBSERVER_PID_FILE, 'r') as f:
  483. pid = int(f.read().strip())
  484. try:
  485. os.kill(pid, 0) # 检查进程是否存在
  486. print(f" ✅ 运行中 (PID: {pid})")
  487. print(f" 📁 服务目录: {WEBSERVER_DIR}")
  488. print(f" 🌐 访问地址: http://localhost:{WEBSERVER_PORT}")
  489. print(f" 📄 首页: http://localhost:{WEBSERVER_PORT}/index.html")
  490. print(" 💡 停止服务: python manage.py stop_webserver")
  491. except OSError:
  492. print(f" ⭕ 未运行 (PID 文件存在但进程不存在)")
  493. os.remove(WEBSERVER_PID_FILE)
  494. print(" 💡 启动服务: python manage.py start_webserver")
  495. except Exception as e:
  496. print(f" ❌ 状态检查失败: {e}")
  497. def show_help():
  498. """显示帮助信息"""
  499. help_text = """
  500. 🐳 TrendRadar 容器管理工具
  501. 📋 命令列表:
  502. run - 手动执行一次爬虫
  503. status - 显示容器运行状态
  504. config - 显示当前配置
  505. files - 显示输出文件
  506. logs - 实时查看日志
  507. restart - 重启说明
  508. start_webserver - 启动 Web 服务器托管 output 目录
  509. stop_webserver - 停止 Web 服务器
  510. webserver_status - 查看 Web 服务器状态
  511. help - 显示此帮助
  512. 📖 使用示例:
  513. # 在容器中执行
  514. python manage.py run
  515. python manage.py status
  516. python manage.py logs
  517. python manage.py start_webserver
  518. # 在宿主机执行
  519. docker exec -it trendradar python manage.py run
  520. docker exec -it trendradar python manage.py status
  521. docker exec -it trendradar python manage.py start_webserver
  522. docker logs trendradar
  523. 💡 常用操作指南:
  524. 1. 检查运行状态: status
  525. - 查看 supercronic 是否为 PID 1
  526. - 检查配置文件和关键文件
  527. - 查看 cron 调度设置
  528. 2. 手动执行测试: run
  529. - 立即执行一次新闻爬取
  530. - 测试程序是否正常工作
  531. 3. 查看日志: logs
  532. - 实时监控运行情况
  533. - 也可使用: docker logs trendradar
  534. 4. 重启服务: restart
  535. - 由于 supercronic 是 PID 1,需要重启整个容器
  536. - 使用: docker restart trendradar
  537. 5. Web 服务器管理:
  538. - 启动: start_webserver
  539. - 停止: stop_webserver
  540. - 状态: webserver_status
  541. - 访问: http://localhost:8080
  542. """
  543. print(help_text)
  544. def main():
  545. if len(sys.argv) < 2:
  546. show_help()
  547. return
  548. command = sys.argv[1]
  549. commands = {
  550. "run": manual_run,
  551. "status": show_status,
  552. "config": show_config,
  553. "files": show_files,
  554. "logs": show_logs,
  555. "restart": restart_supercronic,
  556. "start_webserver": start_webserver,
  557. "stop_webserver": stop_webserver,
  558. "webserver_status": webserver_status,
  559. "help": show_help,
  560. }
  561. if command in commands:
  562. try:
  563. commands[command]()
  564. except KeyboardInterrupt:
  565. print("\n👋 操作已取消")
  566. except Exception as e:
  567. print(f"❌ 执行出错: {e}")
  568. else:
  569. print(f"❌ 未知命令: {command}")
  570. print("运行 'python manage.py help' 查看可用命令")
  571. if __name__ == "__main__":
  572. main()