Python 2.7 使用unicode字符串和不使用unicode方法格式化对象

Python 2.7 使用unicode字符串和不使用unicode方法格式化对象,python-2.7,unicode,utf-8,Python 2.7,Unicode,Utf 8,我经常发现我的自我日志记录对象如下: result = call_a_func(XXX) logger.info(u"I caught an exception {}".format(result)) 问题是,如果结果是一个带有unicode字符字符串(仍然是bytestring)的对象,并且没有\uuuuuUnicode\uuuuuuuu方法,则会爆炸 例如: try: # Exception with a unicode encoded in a string with utf-8

我经常发现我的自我日志记录对象如下:

result = call_a_func(XXX)
logger.info(u"I caught an exception {}".format(result))
问题是,如果结果是一个带有unicode字符字符串(仍然是bytestring)的对象,并且没有
\uuuuuUnicode\uuuuuuuu
方法,则会爆炸

例如:

try:
    # Exception with a unicode encoded in a string with utf-8
    raise Exception("\xea\xb5\xad")  # Note this is not usually created under my control
except Exception as e:
    return u"I captured: {}".format(e)
如果您不确定是否能够将外部库中的对象转换为unicode,那么记录这些对象的最佳方法是什么

有什么比通过以下函数传递更好的方法吗:

def as_unicode(in_obj):
    try:
        return unicode(in_obj)
    except UnicodeDecodeError:
        return str(in_obj).decode("utf-8")

不是真的。如果代码未准备好unicode,那么就没有办法了。不太可能。如果代码未准备好unicode,则对此无能为力。