CCL_QMS检验
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

652 lines
25 KiB

2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import os
  4. import queue
  5. import shutil
  6. import sys
  7. import threading
  8. import time
  9. from datetime import datetime
  10. from pathlib import Path
  11. from tkinter import Tk, Label, Entry, Button, StringVar, END, DISABLED, NORMAL, filedialog, messagebox, simpledialog
  12. from tkinter.scrolledtext import ScrolledText
  13. import requests
  14. from requests.adapters import HTTPAdapter
  15. from urllib3.util.retry import Retry
  16. def get_runtime_dir():
  17. if getattr(sys, "frozen", False):
  18. return Path(sys.executable).resolve().parent
  19. return Path(__file__).resolve().parent
  20. def _ensure_windows_run_registry(entry_name, exe_path):
  21. import winreg
  22. run_key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
  23. target_value = "\"%s\"" % exe_path
  24. try:
  25. with winreg.OpenKey(
  26. winreg.HKEY_CURRENT_USER,
  27. run_key_path,
  28. 0,
  29. winreg.KEY_READ | winreg.KEY_SET_VALUE
  30. ) as key:
  31. try:
  32. old_value, _ = winreg.QueryValueEx(key, entry_name)
  33. except FileNotFoundError:
  34. old_value = None
  35. if old_value and str(old_value).strip().strip("\"").lower() == exe_path.lower():
  36. return False, "系统自启动项已存在,无需重复写入。"
  37. winreg.SetValueEx(key, entry_name, 0, winreg.REG_SZ, target_value)
  38. if old_value:
  39. return True, "检测到自启动路径变化,已自动更新。"
  40. return True, "首次启动已写入系统自启动项,下次开机会自动运行。"
  41. except Exception as e:
  42. return False, "写入系统自启动项失败: %s" % e
  43. def _cleanup_legacy_startup_items(legacy_entry_name, app_data):
  44. if app_data:
  45. startup_dir = Path(app_data) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup"
  46. legacy_script = startup_dir / (legacy_entry_name + ".vbs")
  47. try:
  48. if legacy_script.exists():
  49. legacy_script.unlink()
  50. except Exception:
  51. pass
  52. try:
  53. import winreg
  54. run_key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
  55. with winreg.OpenKey(
  56. winreg.HKEY_CURRENT_USER,
  57. run_key_path,
  58. 0,
  59. winreg.KEY_SET_VALUE
  60. ) as key:
  61. try:
  62. winreg.DeleteValue(key, legacy_entry_name)
  63. except FileNotFoundError:
  64. pass
  65. except Exception:
  66. pass
  67. def ensure_windows_startup():
  68. if os.name != "nt":
  69. return False, "当前系统非Windows,跳过自启动注册。"
  70. if not getattr(sys, "frozen", False):
  71. return False, "当前为源码运行,跳过自启动注册。"
  72. exe_path = str(Path(sys.executable).resolve())
  73. entry_name = "QMSFileCollector"
  74. app_data = os.getenv("APPDATA", "").strip()
  75. _cleanup_legacy_startup_items("CKPClientFileCollector", app_data)
  76. if app_data:
  77. startup_dir = Path(app_data) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup"
  78. startup_script = startup_dir / (entry_name + ".vbs")
  79. script_content = (
  80. "Set WshShell = CreateObject(\"WScript.Shell\")\n"
  81. "WshShell.Run Chr(34) & \"%s\" & Chr(34), 0\n"
  82. "Set WshShell = Nothing\n"
  83. ) % exe_path.replace("\"", "\"\"")
  84. try:
  85. startup_dir.mkdir(parents=True, exist_ok=True)
  86. old_content = ""
  87. if startup_script.exists():
  88. old_content = startup_script.read_text(encoding="utf-8")
  89. if old_content == script_content:
  90. return False, "启动文件夹自启动项已存在,无需重复写入。"
  91. startup_script.write_text(script_content, encoding="utf-8")
  92. if old_content:
  93. return True, "检测到启动文件夹自启动路径变化,已自动更新。"
  94. return True, "首次启动已写入启动文件夹自启动项,下次开机会自动运行。"
  95. except Exception as startup_error:
  96. try:
  97. changed, reg_msg = _ensure_windows_run_registry(entry_name, exe_path)
  98. return changed, "写入启动文件夹失败,已回退注册表方式: %s" % reg_msg
  99. except Exception as reg_error:
  100. return False, "写入启动文件夹和注册表均失败: %s; %s" % (startup_error, reg_error)
  101. try:
  102. return _ensure_windows_run_registry(entry_name, exe_path)
  103. except Exception as e:
  104. return False, "未获取到APPDATA且注册表写入失败: %s" % e
  105. class CollectorApp:
  106. def __init__(self, root):
  107. self.root = root
  108. self.root.title("文件采集客户端")
  109. self.root.geometry("1280x720")
  110. self.root.resizable(True, True)
  111. self.config_path = get_runtime_dir() / "collector_config.json"
  112. self.log_queue = queue.Queue()
  113. self.running = False
  114. self.worker_thread = None
  115. self.stop_event = threading.Event()
  116. self.active_rows = []
  117. self.upload_state = {}
  118. self.notice_ts = {}
  119. self.http_session = self._create_http_session()
  120. self.base_url_var = StringVar()
  121. self.poll_seconds_var = StringVar(value="10")
  122. self.row_vars = []
  123. for _ in range(3):
  124. self.row_vars.append({
  125. "site": StringVar(),
  126. "bu_no": StringVar(),
  127. "equipment_no": StringVar(),
  128. "source_path": StringVar(),
  129. "backup_path": StringVar(),
  130. })
  131. self._build_ui()
  132. self.root.protocol("WM_DELETE_WINDOW", self._on_window_close)
  133. self._init_windows_startup()
  134. self._load_config()
  135. self.root.after(200, self._flush_logs)
  136. self.root.after(3000, self._watch_worker)
  137. def _create_http_session(self):
  138. retry = Retry(
  139. total=3,
  140. connect=3,
  141. read=3,
  142. backoff_factor=1.0,
  143. status_forcelist=[500, 502, 503, 504],
  144. allowed_methods=frozenset(["POST"]),
  145. raise_on_status=False,
  146. )
  147. adapter = HTTPAdapter(max_retries=retry, pool_connections=8, pool_maxsize=8)
  148. session = requests.Session()
  149. session.mount("http://", adapter)
  150. session.mount("https://", adapter)
  151. return session
  152. def _init_windows_startup(self):
  153. changed, message = ensure_windows_startup()
  154. if changed:
  155. self.log(message)
  156. return
  157. if getattr(sys, "frozen", False) and ("失败" in message):
  158. self.log(message)
  159. def _build_ui(self):
  160. Label(self.root, text="系统地址").place(x=20, y=20)
  161. Entry(self.root, textvariable=self.base_url_var, width=92).place(x=85, y=20)
  162. Button(self.root, text="弹框设置地址", command=self.popup_set_base_url).place(x=860, y=16)
  163. Button(self.root, text="保存配置", command=self.save_config).place(x=970, y=16)
  164. Label(self.root, text="轮询秒").place(x=20, y=58)
  165. Entry(self.root, textvariable=self.poll_seconds_var, width=10).place(x=85, y=58)
  166. Button(self.root, text="开始同步", command=self.start_collect).place(x=180, y=54)
  167. Button(self.root, text="停止同步", command=self.stop_collect).place(x=265, y=54)
  168. Button(self.root, text="退出程序", command=self.exit_app).place(x=1080, y=54)
  169. Label(self.root, text="配置说明:最多3行,每行需填写 site + buNo + equipmentNo + 本地目录;备份目录可选(为空则自动使用本地目录_bak)").place(x=360, y=58)
  170. Label(self.root, text="").place(x=20, y=100)
  171. Label(self.root, text="Site").place(x=80, y=100)
  172. Label(self.root, text="BuNo").place(x=220, y=100)
  173. Label(self.root, text="EquipmentNo").place(x=360, y=100)
  174. Label(self.root, text="本地目录").place(x=530, y=100)
  175. Label(self.root, text="备份目录").place(x=890, y=100)
  176. for idx, row in enumerate(self.row_vars):
  177. y = 130 + idx * 40
  178. Label(self.root, text=str(idx + 1)).place(x=26, y=y)
  179. Entry(self.root, textvariable=row["site"], width=16).place(x=80, y=y)
  180. Entry(self.root, textvariable=row["bu_no"], width=16).place(x=220, y=y)
  181. Entry(self.root, textvariable=row["equipment_no"], width=18).place(x=360, y=y)
  182. Entry(self.root, textvariable=row["source_path"], width=40).place(x=530, y=y)
  183. Button(self.root, text="选择目录", command=lambda x=idx: self.choose_source_dir(x)).place(x=815, y=y - 4)
  184. Entry(self.root, textvariable=row["backup_path"], width=30).place(x=890, y=y)
  185. Button(self.root, text="选择目录", command=lambda x=idx: self.choose_backup_dir(x)).place(x=1110, y=y - 4)
  186. self.log_text = ScrolledText(self.root, width=165, height=23)
  187. self.log_text.place(x=20, y=280)
  188. self.log_text.configure(state=DISABLED)
  189. def popup_set_base_url(self):
  190. new_url = simpledialog.askstring(
  191. "设置目标地址",
  192. "请输入xujie-sys地址,例如:http://172.26.58.88:8080",
  193. initialvalue=self.base_url_var.get().strip()
  194. )
  195. if new_url is not None:
  196. self.base_url_var.set(new_url.strip())
  197. self.log("已设置目标地址: %s" % new_url.strip())
  198. def choose_source_dir(self, row_index):
  199. path = filedialog.askdirectory(title="选择第%d行本地目录" % (row_index + 1))
  200. if path:
  201. row = self.row_vars[row_index]
  202. row["source_path"].set(path)
  203. if not row["backup_path"].get().strip():
  204. row["backup_path"].set(self._default_backup_path(path))
  205. def choose_backup_dir(self, row_index):
  206. path = filedialog.askdirectory(title="选择第%d行备份目录" % (row_index + 1))
  207. if path:
  208. self.row_vars[row_index]["backup_path"].set(path)
  209. def _default_backup_path(self, source_path):
  210. source_text = str(source_path).strip()
  211. if not source_text:
  212. return ""
  213. source = Path(source_text)
  214. return str(source.parent / (source.name + "_bak"))
  215. def _load_config(self):
  216. if not self.config_path.exists():
  217. self.log("未找到本地配置,请先录入并保存。")
  218. return
  219. try:
  220. config = json.loads(self.config_path.read_text(encoding="utf-8"))
  221. self.base_url_var.set(config.get("base_url", ""))
  222. self.poll_seconds_var.set(str(config.get("poll_seconds", "10")))
  223. rows = config.get("rows")
  224. # 兼容旧版本单行配置
  225. if not isinstance(rows, list):
  226. rows = [{
  227. "site": config.get("site", ""),
  228. "bu_no": config.get("bu_no", ""),
  229. "equipment_no": config.get("equipment_no", ""),
  230. "source_path": config.get("source_path", ""),
  231. "backup_path": config.get("backup_path", ""),
  232. }]
  233. for idx in range(min(3, len(rows))):
  234. item = rows[idx] if isinstance(rows[idx], dict) else {}
  235. source_path = str(item.get("source_path", "")).strip()
  236. backup_path = str(item.get("backup_path", "")).strip()
  237. if source_path and not backup_path:
  238. backup_path = self._default_backup_path(source_path)
  239. self.row_vars[idx]["site"].set(str(item.get("site", "")).strip())
  240. self.row_vars[idx]["bu_no"].set(str(item.get("bu_no", "")).strip())
  241. self.row_vars[idx]["equipment_no"].set(str(item.get("equipment_no", "")).strip())
  242. self.row_vars[idx]["source_path"].set(source_path)
  243. self.row_vars[idx]["backup_path"].set(backup_path)
  244. self.log("配置加载完成。")
  245. if self._can_auto_start():
  246. self.start_collect(auto_mode=True)
  247. except Exception as e:
  248. self.log("读取配置失败: %s" % e)
  249. def save_config(self):
  250. try:
  251. rows = self._get_valid_rows(require_complete=True, raise_on_empty=False)
  252. except ValueError as e:
  253. messagebox.showwarning("提示", str(e))
  254. return
  255. data = {
  256. "base_url": self.base_url_var.get().strip(),
  257. "poll_seconds": self.poll_seconds_var.get().strip(),
  258. "rows": rows,
  259. }
  260. try:
  261. self.config_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
  262. self.log("配置已保存: %s" % self.config_path)
  263. except Exception as e:
  264. messagebox.showerror("错误", "保存配置失败: %s" % e)
  265. return
  266. if self.running:
  267. self.active_rows = rows
  268. self.log("采集配置已更新,下一轮轮询自动生效。")
  269. elif self._can_auto_start():
  270. self.start_collect(auto_mode=True)
  271. def _can_auto_start(self):
  272. if not self._base_url():
  273. return False
  274. if not self._is_poll_seconds_valid():
  275. return False
  276. try:
  277. rows = self._get_valid_rows(require_complete=True, raise_on_empty=True)
  278. return len(rows) > 0
  279. except Exception:
  280. return False
  281. def _is_poll_seconds_valid(self):
  282. try:
  283. return int(self.poll_seconds_var.get().strip()) > 0
  284. except Exception:
  285. return False
  286. def _base_url(self):
  287. return self.base_url_var.get().strip().rstrip("/")
  288. def _get_valid_rows(self, require_complete, raise_on_empty):
  289. rows = []
  290. for idx, row in enumerate(self.row_vars):
  291. site = row["site"].get().strip()
  292. bu_no = row["bu_no"].get().strip()
  293. equipment_no = row["equipment_no"].get().strip()
  294. source_path = row["source_path"].get().strip()
  295. backup_path = row["backup_path"].get().strip()
  296. filled_count = 0
  297. for value in (site, bu_no, equipment_no, source_path, backup_path):
  298. if value:
  299. filled_count += 1
  300. if filled_count == 0:
  301. continue
  302. required_count = 0
  303. for value in (site, bu_no, equipment_no, source_path):
  304. if value:
  305. required_count += 1
  306. if require_complete and required_count < 4:
  307. raise ValueError("%d行配置未填写完整,请补全site、buNo、equipmentNo、本地目录。" % (idx + 1))
  308. if required_count == 4:
  309. if not backup_path:
  310. backup_path = self._default_backup_path(source_path)
  311. if os.path.normcase(os.path.normpath(source_path)) == os.path.normcase(os.path.normpath(backup_path)):
  312. raise ValueError("%d行配置错误:本地目录和备份目录不能相同。" % (idx + 1))
  313. rows.append({
  314. "row_index": idx + 1,
  315. "site": site,
  316. "bu_no": bu_no,
  317. "equipment_no": equipment_no,
  318. "source_path": source_path,
  319. "backup_path": backup_path,
  320. })
  321. if raise_on_empty and len(rows) == 0:
  322. raise ValueError("请至少填写一行完整采集配置。")
  323. return rows
  324. def start_collect(self, auto_mode=False):
  325. if self.running and self.worker_thread is not None and self.worker_thread.is_alive():
  326. if not auto_mode:
  327. self.log("采集任务已在运行中。")
  328. return
  329. if self.running and (self.worker_thread is None or not self.worker_thread.is_alive()):
  330. self.log("检测到采集线程已退出,正在自动重启。")
  331. self.running = False
  332. if not self._base_url():
  333. if auto_mode:
  334. self.log("自动启动失败:系统地址为空。")
  335. else:
  336. messagebox.showwarning("提示", "请先设置系统地址")
  337. return
  338. try:
  339. poll_seconds = int(self.poll_seconds_var.get().strip() or "10")
  340. if poll_seconds <= 0:
  341. raise ValueError("轮询秒必须大于0")
  342. except Exception:
  343. if auto_mode:
  344. self.log("自动启动失败:轮询秒无效。")
  345. else:
  346. messagebox.showwarning("提示", "轮询秒必须是大于0的整数")
  347. return
  348. try:
  349. rows = self._get_valid_rows(require_complete=True, raise_on_empty=True)
  350. except ValueError as e:
  351. if auto_mode:
  352. self.log("自动启动失败:%s" % e)
  353. else:
  354. messagebox.showwarning("提示", str(e))
  355. return
  356. self.active_rows = rows
  357. # 每次手动/自动启动都重置一次状态,避免停启后误判“已同步”。
  358. self.upload_state = {}
  359. self.notice_ts = {}
  360. self.stop_event = threading.Event()
  361. self.running = True
  362. self.worker_thread = threading.Thread(target=self._worker_loop, args=(self.stop_event,), daemon=True)
  363. self.worker_thread.start()
  364. if auto_mode:
  365. self.log("配置有效,已自动启动轮询同步。")
  366. else:
  367. self.log("采集任务已启动。")
  368. def stop_collect(self):
  369. if not self.running:
  370. self.log("采集任务未运行。")
  371. return
  372. self.running = False
  373. self.stop_event.set()
  374. self.log("正在停止采集任务...")
  375. def _on_window_close(self):
  376. self.root.iconify()
  377. self._log_with_interval("window_hidden", "配置窗口已最小化到任务栏,采集仍在后台运行。", 5)
  378. def exit_app(self):
  379. self.running = False
  380. self.stop_event.set()
  381. try:
  382. self.http_session.close()
  383. except Exception:
  384. pass
  385. self.root.destroy()
  386. def _watch_worker(self):
  387. try:
  388. if self.running and (self.worker_thread is None or not self.worker_thread.is_alive()):
  389. self.log("检测到采集线程中断,正在自动恢复...")
  390. self.running = False
  391. self.start_collect(auto_mode=True)
  392. finally:
  393. self.root.after(3000, self._watch_worker)
  394. def _worker_loop(self, stop_event):
  395. while not stop_event.is_set():
  396. try:
  397. rows = list(self.active_rows)
  398. for row in rows:
  399. if stop_event.is_set():
  400. break
  401. try:
  402. self._sync_one_row(row, stop_event)
  403. except Exception as row_error:
  404. self.log("%d行同步异常,已跳过并继续: %s" % (row.get("row_index", 0), row_error))
  405. try:
  406. poll_seconds = int(self.poll_seconds_var.get().strip() or "10")
  407. except Exception:
  408. poll_seconds = 10
  409. for _ in range(max(1, poll_seconds)):
  410. if stop_event.is_set():
  411. break
  412. time.sleep(1)
  413. except Exception as e:
  414. self.log("采集线程异常,将自动继续: %s" % e)
  415. for _ in range(5):
  416. if stop_event.is_set():
  417. break
  418. time.sleep(1)
  419. if self.stop_event is stop_event:
  420. self.running = False
  421. self.worker_thread = None
  422. self.log("采集任务已停止。")
  423. def _sync_one_row(self, row, stop_event):
  424. row_index = row["row_index"]
  425. source_path = row["source_path"]
  426. path_key = "row%d_missing" % row_index
  427. empty_key = "row%d_empty" % row_index
  428. if not os.path.isdir(source_path):
  429. self._log_with_interval(path_key, "%d行目录不存在: %s" % (row_index, source_path), 60)
  430. return
  431. files = []
  432. try:
  433. for name in os.listdir(source_path):
  434. file_path = Path(source_path) / name
  435. if file_path.is_file():
  436. files.append(file_path)
  437. except Exception as e:
  438. self._log_with_interval(path_key, "%d行读取目录失败: %s, 原因: %s" % (row_index, source_path, e), 30)
  439. return
  440. self._cleanup_row_upload_state(row_index, files)
  441. if not files:
  442. self._log_with_interval(empty_key, "%d行目录为空,等待新文件..." % row_index, 60)
  443. return
  444. files.sort(key=self._safe_mtime)
  445. for file_path in files:
  446. if stop_event.is_set():
  447. return
  448. signature = self._file_signature(file_path)
  449. if signature is None:
  450. continue
  451. state_key = "%d|%s" % (row_index, str(file_path).lower())
  452. if self.upload_state.get(state_key) == signature:
  453. continue
  454. if self._upload_file(row, file_path):
  455. if self._backup_and_remove_file(row, file_path):
  456. # 文件已从源目录移走,立即清理状态,允许后续同名新文件再次同步。
  457. self.upload_state.pop(state_key, None)
  458. else:
  459. self.upload_state.pop(state_key, None)
  460. def _cleanup_row_upload_state(self, row_index, files):
  461. prefix = "%d|" % row_index
  462. current_keys = set()
  463. for file_path in files:
  464. current_keys.add("%d|%s" % (row_index, str(file_path).lower()))
  465. stale_keys = []
  466. for key in self.upload_state.keys():
  467. if key.startswith(prefix) and key not in current_keys:
  468. stale_keys.append(key)
  469. for key in stale_keys:
  470. self.upload_state.pop(key, None)
  471. def _file_signature(self, file_path):
  472. try:
  473. stat = file_path.stat()
  474. return stat.st_mtime_ns, stat.st_size
  475. except Exception as e:
  476. self.log("读取文件状态失败: %s, 原因: %s" % (file_path, e))
  477. return None
  478. def _safe_mtime(self, file_path):
  479. try:
  480. return file_path.stat().st_mtime
  481. except Exception:
  482. return 0
  483. def _get_backup_dir(self, row):
  484. backup_path = str(row.get("backup_path", "")).strip()
  485. if backup_path:
  486. return Path(backup_path)
  487. return Path(self._default_backup_path(row["source_path"]))
  488. def _backup_and_remove_file(self, row, file_path):
  489. source_path = row["source_path"]
  490. row_index = row["row_index"]
  491. backup_dir = self._get_backup_dir(row)
  492. if os.path.normcase(os.path.normpath(str(source_path))) == os.path.normcase(os.path.normpath(str(backup_dir))):
  493. self.log("%d行备份目录不能与本地目录相同: %s" % (row_index, backup_dir))
  494. return False
  495. try:
  496. backup_dir.mkdir(parents=True, exist_ok=True)
  497. except Exception as e:
  498. self.log("%d行创建备份目录失败: %s, 原因: %s" % (row_index, backup_dir, e))
  499. return False
  500. target = backup_dir / file_path.name
  501. if target.exists():
  502. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  503. target = backup_dir / ("%s_%s%s" % (file_path.stem, timestamp, file_path.suffix))
  504. try:
  505. shutil.move(str(file_path), str(target))
  506. self.log("%d行源文件已转移至备份: %s -> %s" % (row_index, file_path.name, target))
  507. return True
  508. except Exception as e:
  509. self.log("%d行源文件备份转移失败: %s, 原因: %s" % (row_index, file_path.name, e))
  510. return False
  511. def _upload_file(self, row, file_path):
  512. url = self._base_url() + "/collector/client/upload"
  513. data = {
  514. "site": row["site"],
  515. "buNo": row["bu_no"],
  516. "equipmentNo": row["equipment_no"],
  517. }
  518. try:
  519. with open(file_path, "rb") as fp:
  520. files = {"file": (file_path.name, fp, "application/octet-stream")}
  521. resp = self.http_session.post(url, data=data, files=files, timeout=180)
  522. resp.raise_for_status()
  523. result = resp.json()
  524. if result.get("code") == 0:
  525. response_data = result.get("data") or {}
  526. server_path = response_data.get("savedFullPath", "")
  527. self.log("%d行上传成功: %s -> %s" % (row["row_index"], file_path.name, server_path))
  528. return True
  529. self.log("%d行上传失败: %s, 原因: %s" % (
  530. row["row_index"], file_path.name, result.get("msg")))
  531. return False
  532. except Exception as e:
  533. self.log("%d行上传异常: %s, 原因: %s" % (row["row_index"], file_path.name, e))
  534. return False
  535. def _log_with_interval(self, key, message, seconds):
  536. now = time.time()
  537. last = self.notice_ts.get(key, 0)
  538. if now - last >= seconds:
  539. self.notice_ts[key] = now
  540. self.log(message)
  541. def log(self, message):
  542. self.log_queue.put("[%s] %s" % (datetime.now().strftime("%H:%M:%S"), message))
  543. def _flush_logs(self):
  544. while not self.log_queue.empty():
  545. line = self.log_queue.get()
  546. self.log_text.configure(state=NORMAL)
  547. self.log_text.insert(END, line + "\n")
  548. self.log_text.see(END)
  549. self.log_text.configure(state=DISABLED)
  550. self.root.after(200, self._flush_logs)
  551. if __name__ == "__main__":
  552. app_root = Tk()
  553. app = CollectorApp(app_root)
  554. app_root.mainloop()