相关疑难解决方法(0)

在Python 2中跟踪隐式unicode转换

我有一个大型项目,在各个地方有问题的隐式Unicode转换(coersions)以例如:

someDynamicStr = "bar" # could come from various sources

# works
u"foo" + someDynamicStr
u"foo{}".format(someDynamicStr)

someDynamicStr = "\xff" # uh-oh

# raises UnicodeDecodeError
u"foo" + someDynamicStr
u"foo{}".format(someDynamicStr)
Run Code Online (Sandbox Code Playgroud)

(也可能是其他形式.)

现在我想跟踪这些用法,特别是那些积极使用的代码.

如果我可以轻松地unicode用一个包装器替换构造函数会很好,它会检查输入是否为type str并且encoding/ errorsparameters设置为默认值然后通知我(打印回溯等).

/编辑:

虽然没有直接关系的东西我找我碰到了如何使解码异常干脆离开这个光荣可怕的黑客(解码一个唯一的,即str到unicode,而不是周围的其他方法,请参阅https://开头的邮件. python.org/pipermail/python-list/2012-July/627506.html).

我不打算使用它,但对于那些与无效的Unicode输入和寻找快速修复(但请考虑副作用)的问题进行斗争可能会很有趣:

import codecs
codecs.register_error("strict", codecs.ignore_errors)
codecs.register_error("strict", lambda x: (u"", x.end)) # alternatively
Run Code Online (Sandbox Code Playgroud)

(互联网搜索codecs.register_error("strict"显示它显然用于某些真实项目.)

/编辑#2:

对于显式转换,我在monkeypatching的SO帖子的帮助下制作了一个片段:

class PatchedUnicode(unicode):
  def __init__(self, obj=None, encoding=None, *args, **kwargs):
    if encoding in (None, "ascii", …
Run Code Online (Sandbox Code Playgroud)

python debugging unicode monkeypatching python-2.7

8
推荐指数
1
解决办法
746
查看次数

标签 统计

debugging ×1

monkeypatching ×1

python ×1

python-2.7 ×1

unicode ×1