-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathembedded_monitor.py
More file actions
68 lines (59 loc) · 1.94 KB
/
embedded_monitor.py
File metadata and controls
68 lines (59 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
内嵌文件监控脚本 - 用于打包环境
"""
import os
import time
import sys
import codecs
from pathlib import Path
def optimized_monitor(file_path, task_name):
"""高效的文件监控函数"""
print(f"开始监控文件: {file_path}")
print(f"任务名称: {task_name}")
print("=" * 60)
# 等待文件创建
while not os.path.exists(file_path):
print("等待文件创建...")
time.sleep(1)
print(f"文件已创建: {file_path}")
try:
decoder = codecs.getincrementaldecoder('utf-8')('ignore')
with open(file_path, 'rb') as f:
f.seek(0, os.SEEK_END)
leftover = ''
while True:
chunk = f.read(65536)
if chunk:
text = decoder.decode(chunk)
if text:
buf = leftover + text
lines = buf.splitlines(True)
if lines and not (lines[-1].endswith('\n') or lines[-1].endswith('\r')):
leftover = lines.pop()
else:
leftover = ''
for line in lines:
print(f"[{time.strftime('%H:%M:%S')}] {line.rstrip()}")
sys.stdout.flush()
else:
time.sleep(0.05)
except KeyboardInterrupt:
print("\n监控已停止")
except Exception as e:
print(f"监控出错: {e}")
time.sleep(1)
def main():
"""主函数 - 用于独立运行"""
if len(sys.argv) != 3:
print("用法: python embedded_monitor.py <文件路径> <任务名称>")
sys.exit(1)
file_path = sys.argv[1]
task_name = sys.argv[2]
try:
optimized_monitor(file_path, task_name)
except Exception as e:
print(f"监控出错: {e}")
if __name__ == "__main__":
main()