如何在Python脚本中记录所有命令行错误?无需逐行加try catch块
解决Python全局错误捕获与日志记录的几种实用方案
不用给每行代码加try-except,这几种方法能帮你批量捕获并记录所有错误:
1. 全局异常钩子(sys.excepthook)
直接替换Python默认的异常处理逻辑,能捕获所有未被局部try-except处理的异常,统一打日志。
示例代码:
import sys import logging # 配置日志输出 logging.basicConfig( level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s', filename='global_errors.log' ) logger = logging.getLogger(__name__) def global_error_handler(exc_type, exc_value, exc_traceback): # 排除Ctrl+C这类主动中断的异常 if issubclass(exc_type, KeyboardInterrupt): sys.__excepthook__(exc_type, exc_value, exc_traceback) return # 记录异常详情(包括堆栈) logger.error("未捕获的异常", exc_info=(exc_type, exc_value, exc_traceback)) # 替换默认的异常处理钩子 sys.excepthook = global_error_handler # 测试:这段代码出错会被自动捕获 def risky_op(): return 1 / 0 risky_op()
2. 函数装饰器批量处理
写一个通用装饰器,给需要监控的函数套上,自动捕获函数内的所有异常并记录,不用每个函数写重复的try-except。
示例代码:
import logging logging.basicConfig( level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s', filename='func_errors.log' ) logger = logging.getLogger(__name__) def log_func_exceptions(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logger.error(f"函数[{func.__name__}]执行失败: {str(e)}", exc_info=True) # 要是需要让上层感知异常,就打开下面的raise # raise return wrapper # 给需要监控的函数加装饰器 @log_func_exceptions def compare_data(a, b): if a["id"] != b["id"]: raise ValueError("ID不匹配") return True # 测试触发异常 compare_data({"id":1}, {"id":2})
3. 上下文管理器包裹代码块
如果只是某一段代码需要统一监控,用上下文管理器包裹,灵活度高,不用嵌套try-except。
示例代码:
import logging from contextlib import contextmanager logging.basicConfig( level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s', filename='block_errors.log' ) logger = logging.getLogger(__name__) @contextmanager def log_block_errors(block_name): try: yield except Exception as e: logger.error(f"代码块[{block_name}]执行出错: {str(e)}", exc_info=True) # 可选:是否重新抛出异常 # raise # 使用上下文管理器包裹需要监控的代码 with log_block_errors("用户数据对比"): data1 = {"name": "Alice"} data2 = {"age": 25} if data1["name"] != data2["name"]: raise KeyError("name字段缺失或不匹配")
总结
- 要覆盖全局所有未处理异常:用
sys.excepthook - 只针对特定函数监控:用装饰器
- 临时包裹某段代码块:用上下文管理器
这三种方法都不用逐行加try-except,能满足你记录所有错误的需求。
内容的提问来源于stack exchange,提问作者Manav Suhange
相关产品推荐
相关产品推荐

