python - 在将字符串强制转换为 unicode 时如何让 python 2.x 发出警告?

标签 python unicode python-2.x

一个非常常见的编码错误来源是,当您将字符串与 unicode 相加时,python 2 会默默地将字符串强制转换为 unicode。这会导致混合编码问题,并且很难调试。

例如:

import urllib
import webbrowser
name = raw_input("What's your name?\nName: ")
greeting = "Hello, %s" % name
if name == "John":
    greeting += u' (Feliz cumplea\xf1os!)'
webbrowser.open('http://lmgtf\x79.com?q=' + urllib.quote_plus(greeting))

如果您输入“John”,将会失败并出现神秘错误:

/usr/lib/python2.7/urllib.py:1268: UnicodeWarning: Unicode equal comparison faile
d to convert both arguments to Unicode - interpreting them as being unequal
  return ''.join(map(quoter, s))
Traceback (most recent call last):
  File "feliz.py", line 7, in <module>
    webbrowser.open('http://lmgtf\x79.com?q=' + urllib.quote_plus(greeting))
  File "/usr/lib/python2.7/urllib.py", line 1273, in quote_plus
    s = quote(s, safe + ' ')
  File "/usr/lib/python2.7/urllib.py", line 1268, in quote
    return ''.join(map(quoter, s))
KeyError: u'\xf1'

当实际错误与实际强制转换发生的位置相去甚远时,追踪起来就特别困难。

当字符串被强制转换为 unicode 时,如何配置 python 立即发出警告或异常?

最佳答案

在问了这个问题后我做了更多的研究并找到了完美的答案。 Armin Ronacher 创造了一个很棒的小工具,叫做 unicode-nazi .只需安装它并像这样运行您的程序:

python -Werror -municodenazi myprog.py

然后您会在强制转换发生的地方获得追溯:

Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "SITE-PACKAGES/unicodenazi.py", line 128, in <module>
    main()
  File "SITE-PACKAGES/unicodenazi.py", line 119, in main
    execfile(sys.argv[0], main_mod.__dict__)
  File "myprog.py", line 4, in <module>
    print foo()
  File "myprog.py", line 2, in foo
    return 'bar' + u'baz'
  File "SITE-PACKAGES/unicodenazi.py", line 34, in warning_decode
    stacklevel=2)
UnicodeWarning: Implicit conversion of str to unicode

如果您正在处理自身触发隐式强制转换的 python 库,并且您无法捕获异常或以其他方式解决它们,则可以省略 -Werror:

python -municodenazi myprog.py

并且至少在它发生时在 stderr 上看到打印出的警告:

/SITE-PACKAGES/unicodenazi.py:119: UnicodeWarning: Implicit conversion of str to unicode
  execfile(sys.argv[0], main_mod.__dict__)
barbaz

关于python - 在将字符串强制转换为 unicode 时如何让 python 2.x 发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557447/

相关文章:

Python 异常排序

python - 在 SymPy 中用 (-M) 替换矩阵 M 并明确显示它

python - Cygwin:导入 numpy 错误

python - 为什么 python 的 monkeypatch 在导入类而不是模块时不起作用?

java - 将 unicode 字符串拆分为字符串列表

python - 如何在 python 3.6 中打开混合编码的 unicode 文件?

python - Tkinter 尝试使用 StringVars 显示日历日期时出现问题

python - 自定义类排序 : no error thrown, 什么是 Python 测试?

python - 修改 Tkinter 条目小部件时如何获取事件回调?

pdf - 带有 PDF 和 Unicode(希腊语)字符的 Jasper 报告