55import win32gui
66import win32process
77import pymsgbox
8+ import traceback
89# from subprocess import PIPE, Popen
910# python调用命令行:https://zhuanlan.zhihu.com/p/329957363
1011import clr
@@ -138,7 +139,14 @@ def get_json(json_filename):
138139 with open (json_filename , "r" , encoding = "utf8" ) as f :
139140 json_text = f .read ()
140141 if json_text != "" :
141- json_obj = json .loads (json_text )
142+ try :
143+ json_obj = json .loads (json_text )
144+ except Exception as e :
145+ pymsgbox .alert (f"window_monitor 打开json失败:{ json_filename } \n "
146+ "建议检查json文件然后重新运行本程序\n "
147+ "(注:通常是资源管理器卡死或重启或程序异常中止导致的写入异常,需将两份历史记录手动同步)" , "window_monitor" )
148+ # raise
149+ exit ()
142150 else :
143151 print (f"{ json_filename } 文件为空,get_json读取为[]" )
144152 json_obj = []
@@ -179,8 +187,8 @@ def save_last_hwnd_all_to_history(a_last):
179187 write_obj_to_json (all_history , program_history_json )
180188
181189# 保留10000条记录,每3秒记录一次,共约8.3小时
182- if __name__ == "__main__" :
183- # def program_main():
190+ def program_main () :
191+ global last_hwnd_all , max_history_length , seconds_per_loop
184192 cfg = get_json (config_json )
185193 max_history_length = cfg ["max_history_length" ]
186194 seconds_per_loop = cfg ["seconds_per_loop" ]
@@ -209,4 +217,18 @@ def save_last_hwnd_all_to_history(a_last):
209217 time .sleep (seconds_per_loop / 2 )
210218 # os.system("pause")
211219 dbg = 1
220+
221+ if __name__ == "__main__" :
222+ is_debugging = sys .gettrace ()
223+ if is_debugging : # vscode拉起调试中,暴露错误信息
224+ program_main ()
225+ else : # 没有在调试,打印错误信息
226+ try :
227+ program_main ()
228+ except Exception as e :
229+ error_str = traceback .format_exc ()
230+ log (f"{ type (e ).__name__ } : { str (e )} \n { error_str } " )
231+ pymsgbox .alert (error_str , "window_monitor: 发生错误" )
232+ dbg = 1
233+
212234a = 1
0 commit comments