traceback.print_stack(file=sys.stdout)找程序流程

本文介绍了一个具体的调试场景,展示了如何通过打印堆栈跟踪和详细记录输入缓冲区内容来定位问题。这种方法有助于理解程序运行时的状态,并能有效地进行错误排查。

def do_event_in(self, buf):
        traceback.print_stack(file=sys.stdout)
        s =  traceback.extract_stack()
        print '%s Invoked me!'%s[-2][2]
        log_debug('server in %s' % buf)
        buf.clear()
        self.push()
        return 0

 File "./tcp_server.py", line 139, in <module>
    unit.start()
  File "/data/dreamliang/mySvn/sdn_proj/branches/oss/common/poller_timer_unit.py", line 23, in start
    CPollerUnit.process_poller_events(self)
  File "/data/dreamliang/mySvn/sdn_proj/branches/oss/common/poller.py", line 207, in process_poller_events
    if epoll_object.input_notify() >= 0:
  File "./tcp_server.py", line 95, in input_notify
    ret = server_conn_object.init(server_conn, self)
  File "./tcp_server.py", line 29, in init
    return self.push()
  File "/data/dreamliang/mySvn/sdn_proj/branches/oss/common/tcp_base_connect.py", line 42, in push
    if self._conn is None: ret = self.create_conn()
  File "./tcp_server.py", line 38, in create_conn
    if not self.b_use_oob(): self.input_notify()
  File "./tcp_server.py", line 42, in input_notify
    return CTcpBaseConnect.input_notify(self)
  File "/data/dreamliang/mySvn/sdn_proj/branches/oss/common/tcp_base_connect.py", line 143, in input_notify
    return self.do_event_in()
  File "/data/dreamliang/mySvn/sdn_proj/branches/oss/common/tcp_base_connect.py", line 121, in do_event_in
    ret = self.handle_event_in()
  File "/data/dreamliang/mySvn/sdn_proj/branches/oss/common/tcp_base_connect.py", line 111, in handle_event_in
    ret = self._handle.do_event_in(self._in_buf)
  File "/data/dreamliang/mySvn/sdn_proj/branches/oss/common/tcp_handle.py", line 136, in do_event_in
    traceback.print_stack(file=sys.stdout)
handle_event_in Invoked me!

Traceback (most recent call last): File "/data/zihao.zhang/DM_ICC/CDDM/main.py", line 5, in <module> File "/data/zihao.zhang/DM_ICC/CDDM/Diffusion/__init__.py", line 3, in <module> from .Diffusion import * File "/data/zihao.zhang/DM_ICC/CDDM/Diffusion/Diffusion.py", line 3, in <module> import torch File "/opt/conda/lib/python3.8/site-packages/torch/__init__.py", line 537, in <module> _C._initExtension(manager_path()) File "/opt/conda/lib/python3.8/site-packages/torch/cuda/__init__.py", line 123, in <module> _lazy_call(_check_capability) File "/opt/conda/lib/python3.8/site-packages/torch/cuda/__init__.py", line 121, in _lazy_call _queued_calls.append((callable, traceback.format_stack())) File "/opt/conda/lib/python3.8/traceback.py", line 197, in format_stack return format_list(extract_stack(f, limit=limit)) File "/opt/conda/lib/python3.8/traceback.py", line 211, in extract_stack stack = StackSummary.extract(walk_stack(f), limit=limit) File "/opt/conda/lib/python3.8/traceback.py", line 366, in extract f.line File "/opt/conda/lib/python3.8/traceback.py", line 288, in line self._line = linecache.getline(self.filename, self.lineno).strip() File "/opt/conda/lib/python3.8/linecache.py", line 16, in getline lines = getlines(filename, module_globals) File "/opt/conda/lib/python3.8/linecache.py", line 47, in getlines return updatecache(filename, module_globals) File "/opt/conda/lib/python3.8/linecache.py", line 137, in updatecache lines = fp.readlines() File "/opt/conda/lib/python3.8/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 294-295: invalid continuation byte
最新发布
09-05
将下列代码报错的日志进行保存ef get_image(): try: # 清理上传目录中的JPEG文件 for filename in os.listdir(uploads_path): if filename.endswith('.jpg'): file_path = os.path.join(uploads_path, filename) os.remove(file_path) # 简化删除逻辑,异常将被外层捕获 # 重置全局状态 global RESET_TIME RESET_TIME = True # 获取并验证JSON数据 json_data = request.get_json() if not json_data or 'data' not in json_data or 'data' not in json_data['data']: logging.error("无效的JSON格式:缺少'data.data'字段") raise ValueError("无效的JSON格式:缺少'data.data'字段") up_file = json_data["data"]["data"] saved_images = [] # 处理每个上传的图像 for image_id, value in up_file.items(): # 安全过滤图像ID,只保留字母数字和部分安全字符 safe_id = ''.join(e for e in image_id if e.isalnum() or e in ['_', '-']) if not safe_id: logging.error(f"Invalid image ID: {image_id}") raise ValueError(f"Invalid image ID: {image_id}") up_filename = safe_id + ".jpg" save_file = os.path.join(uploads_path, up_filename) # 解码Base64数据 try: image_data = base64.b64decode(value) except (base64.binascii.Error, TypeError) as e: logging.error(f"ID为{safe_id}的图像数据解码失败: {str(e)}") raise ValueError(f"ID为{safe_id}的图像数据解码失败: {str(e)}") # 打开并验证图像 try: image = Image.open(BytesIO(image_data)) image.verify() # 验证图像完整性 image = Image.open(BytesIO(image_data)) # 验证后重新打开 except UnidentifiedImageError as e: logging.error(f"图像破损 ID {safe_id}: {str(e)}") raise ValueError(f"图像破损 ID {safe_id}: {str(e)}") except Exception as e: logging.error(f"Failed to process image ID {safe_id}: {str(e)}") raise ValueError(f"Failed to process image ID {safe_id}: {str(e)}") # 保存图像 try: image.save(save_file) except Exception as e: logging.error(f"Failed to save image ID {safe_id} to {save_file}: {str(e)}") raise ValueError(f"Failed to save image ID {safe_id} to {save_file}: {str(e)}") saved_images.append((safe_id, save_file)) # 检查是否有成功保存的图像 if not saved_images: logging.error("没有图像被成功处理") raise ValueError("没有图像被成功处理") return saved_images[-1][0], saved_images[-1][1] except Exception as e: logging.error(f'Critical error in get_image: {str(e)}') # 可以在这里添加更多的错误日志记录 print(f'Critical error in get_image: {str(e)}') raise # 重新抛出异常,让调用者处理 @app.route("/api/YuHangAI/picture/v2.0/",methods=['GET','POST']) def interface_usage(): message = """<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>北京御航智能</title> </head> <body> <h1>北京御航智能图像智能识别服务接口</h1> <p>提供多种场景下的图像识别</p> </body> </html>""" return message # 输电识别模型, 无人机巡检场景 @app.route("/api/YuHangAI/picture/v2.0/transmission",methods=['POST']) def detect_transmission_image(): logger.info("输电缺陷识别") start_time = time.time() json_data = request.get_json() try: _type = json_data["type"] except: _type = False image_id, save_file = get_image() time_1 = time.time() logger.info(f"处理数据用时{time_1-start_time}s") print(f"处理数据用时",file = sys.stderr) if save_file is None: logging.error('不支持的图像类型!') return jsonify("不支持的图像类型!") try: if _type == "wrjwyy": out_json = {"results":[]} out_json["data"]=preprocessing(save_file) else: out_json = {'image_id':image_id} objects = pool.apply_async(func=detect_transmission_models,args=(save_file,)).get() # result = pool.apply_async(func=detect_transmission_models, args=(save_file,)) # objects = result.get(timeout=30) count = 0 if len(objects) > 0: for key, values in objects.items(): if _type == "wrjwyy": if key in name_map: for value in values: if value[4] > 0.7: value.append(name_map[key]) out_json["results"].append({"result":value}) else: for value in values: if value[4] < 0.7: continue value.append(key) out_json[str(count)] = {"result":value} count += 1 except torch.cuda.OutOfMemoryError: logging.error("CUDA内存不足错误") out_json['status'] = '检测任务失败:GPU内存不足' except FileNotFoundError: logging.error(f"文件不存在: {save_file}") out_json['status'] = '检测任务失败:文件不存在' except Exception as e: import traceback logging.error(traceback.format_exc()) out_json['status'] = '检测任务失败!'+str(e) logging.error('检测任务失败!'+str(e)) time_2 = time.time() logger.info(f"检测图片用时{time_2-time_1}s") # print(f'检测图片用时{time_2-time_1}s',file = stdout) try: os.remove(save_file) except Exception as e: # logger.info('Failed to delete %s. Reason: %s' % (save_file, e)) print('Failed to delete %s. Reason: %s' % (save_file, e)) return jsonify(out_json)
08-07
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 330, in find_cookie line_string = line.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 25: invalid continuation byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "_pydevd_bundle/pydevd_cython.pyx", line 532, in _pydevd_bundle.pydevd_cython.PyDBFrame._handle_exception File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 16, in getline lines = getlines(filename, module_globals) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 47, in getlines return updatecache(filename, module_globals) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 136, in updatecache with tokenize.open(fullname) as fp: File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 394, in open encoding, lines = detect_encoding(buffer.readline) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 381, in detect_encoding encoding = find_cookie(second) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 335, in find_cookie raise SyntaxError(msg) SyntaxError: invalid or missing encoding declaration for 'D:\\project\\desktop_jijun\\desktop_jijun\\desktop_jijun.py' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 330, in find_cookie line_string = line.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 25: invalid continuation byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "D:\project\desktop_jijun\desktop_jijun\desktop_jijun.py", line 169, in consaltant content = response.content.decode('gbk') File "_pydevd_bundle/pydevd_cython.pyx", line 1366, in _pydevd_bundle.pydevd_cython.SafeCallWrapper.__call__ File "_pydevd_bundle/pydevd_cython.pyx", line 322, in _pydevd_bundle.pydevd_cython.PyDBFrame.trace_exception File "_pydevd_bundle/pydevd_cython.pyx", line 452, in _pydevd_bundle.pydevd_cython.PyDBFrame.handle_user_exception File "_pydevd_bundle/pydevd_cython.pyx", line 535, in _pydevd_bundle.pydevd_cython.PyDBFrame._handle_exception File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 16, in getline lines = getlines(filename, module_globals) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 47, in getlines return updatecache(filename, module_globals) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 136, in updatecache with tokenize.open(fullname) as fp: File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 394, in open encoding, lines = detect_encoding(buffer.readline) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 381, in detect_encoding encoding = find_cookie(second) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 335, in find_cookie raise SyntaxError(msg) SyntaxError: invalid or missing encoding declaration for 'D:\\project\\desktop_jijun\\desktop_jijun\\desktop_jijun.py' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 330, in find_cookie line_string = line.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 25: invalid continuation byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "d:\vs\benti\common7\ide\extensions\microsoft\python\core\debugpy\__main__.py", line 45, in <module> cli.main() File "d:\vs\benti\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 444, in main run() File "d:\vs\benti\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 285, in run_file runpy.run_path(target_as_str, run_name=compat.force_str("__main__")) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 265, in run_path return _run_module_code(code, init_globals, run_name, File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "D:\project\desktop_jijun\desktop_jijun\desktop_jijun.py", line 197, in <module> root.mainloop() File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1420, in mainloop self.tk.mainloop(n) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1887, in __call__ self.widget._report_exception() File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1603, in _report_exception root.report_callback_exception(exc, val, tb) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2341, in report_callback_exception traceback.print_exception(exc, val, tb) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 103, in print_exception for line in TracebackException( File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 509, in __init__ self.stack = StackSummary.extract( File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 366, in extract f.line File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 288, in line self._line = linecache.getline(self.filename, self.lineno).strip() File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 16, in getline lines = getlines(filename, module_globals) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 47, in getlines return updatecache(filename, module_globals) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 136, in updatecache with tokenize.open(fullname) as fp: File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 394, in open encoding, lines = detect_encoding(buffer.readline) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 381, in detect_encoding encoding = find_cookie(second) File "C:\Users\lry20\AppData\Local\Programs\Python\Python38\lib\tokenize.py", line 335, in find_cookie raise SyntaxError(msg) SyntaxError: invalid or missing encoding declaration for 'D:\\project\\desktop_jijun\\desktop_jijun\\desktop_jijun.py' a Press any key t
06-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值