Azure Databricks中Python Exception的<=>字符丢失问题求助
问题描述
我们在Azure Databricks环境开发Python库,用于生成SQL MERGE字符串,通过自定义DebugMode异常返回该SQL串。遇到一个奇怪的问题:打印该异常字符串时,<=>字符会丢失,但展开异常详情后,这个字符又能正常显示。
可复现的测试代码:
raise Exception('this is a string with the dreaded spaceship <=> < > <= >= `<=>` - = + / <random> \<rand2>')
自定义DebugMode异常类代码:
class DebugMode(Exception): ''' Exception raised in the event of debug mode being enabled on any of the merge functions. It is intended to halt the merge and provide the SQL merge string for manual review. Attributes: sql_string (str): The sql merge string produced by the merge function. Methods: None ''' def __init__(self, sql_string, message='Debug mode was enabled, the SQL operation has halted to allow manual review of the SQL string below.'): self.sql_string = sql_string self.message = message super().__init__(self.message) # overwrite the Exception base classe's message def __str__(self): return f'{self.message}\n{self.sql_string}'
问题原因与解决办法
原因
Azure Databricks的异常展示界面会对顶部的异常摘要做HTML转义处理,<=>会被识别为类似HTML标签的结构,被自动过滤隐藏;而展开异常详情后,会直接展示原始字符串内容,所以<=>能正常显示。另外,当前自定义异常的初始化逻辑只把message传给父类构造函数,导致异常默认摘要仅包含message,sql_string里的特殊字符在摘要展示时被处理。
解决办法
1. 修改异常初始化逻辑,传递完整内容给父类
在DebugMode的__init__方法中,把包含sql_string的完整字符串传给父类构造函数,确保异常顶部摘要显示完整内容:
class DebugMode(Exception): ''' Exception raised in the event of debug mode being enabled on any of the merge functions. It is intended to halt the merge and provide the SQL merge string for manual review. Attributes: sql_string (str): The sql merge string produced by the merge function. Methods: None ''' def __init__(self, sql_string, message='Debug mode was enabled, the SQL operation has halted to allow manual review of the SQL string below.'): self.sql_string = sql_string self.message = message # 把完整组合字符串传给父类,让异常摘要包含SQL内容 full_message = f'{self.message}\n{self.sql_string}' super().__init__(full_message) def __str__(self): return f'{self.message}\n{self.sql_string}'
2. 对SQL字符串中的特殊字符转义
如果不想修改异常类逻辑,可以在生成或传入sql_string时,将<替换为<,>替换为>,这样在HTML展示时会正确解析为原始字符:
# 处理SQL字符串中的特殊字符 sql_string = sql_string.replace('<', '<').replace('>', '>')
注意:这种方式会让原始字符串带有转义字符,适合仅需界面展示的场景。
3. 手动打印异常的字符串结果
捕获异常时,不依赖Databricks的默认展示,直接手动打印str(异常实例),输出原始字符串:
try: # 触发DebugMode异常的业务逻辑 raise DebugMode("SELECT * FROM table WHERE col1 <=> col2") except DebugMode as e: print(str(e))
内容的提问来源于stack exchange,提问作者FoxHound
相关产品推荐
相关产品推荐

