gpt4 book ai didi

python-2.7 - Python 2.7 异常不处理 python3 兼容代码中的 unicode ('' )

转载 作者:行者123 更新时间:2023-12-02 01:08:59 24 4
gpt4 key购买 nike

我正在尝试使用与 python2.7/3+ 兼容的代码。而且我正在努力正确处理使用 unicode 消息引发 ValueError 的问题。我发现“异常 str() 失败”的结果很少。

这是代码:

from __future__ import (
absolute_import, division, print_function, unicode_literals
)

import logging

from builtins import str
from future import standard_library

standard_library.install_aliases()

conf = {}
try:
conf["key"]
except KeyError:
msg = "Message"
msg += " + ünicode"
logging.warn(msg)
raise ValueError(msg)

在 python3 中,这是按预期工作的,但在 python 2.7 中,只要 msg包含它给出的 unicode:
WARNING:root:Message + ünicode
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
ValueError: <exception str() failed>

请注意日志记录如何处理 unicode 字符串而不是 ValueError .我究竟做错了什么 ?如何在 python 2.7 和 3+ 中都有 unicode 错误消息?

最佳答案

您可以尝试对 msg 进行编码,将其转换为 Python 2 的字符串,例如

from sys import version_info

if version_info.major == 2:
raise ValueError(msg.encode('utf-8'))
elif version_info.major == 3:
raise ValueError(msg)
else:
raise YourException("not supported Python version")

Upate:如果您只使用 from __future__ import unicode_literals,以下是不导入任何包的解决方法没有 python-future包裹:
if isinstance(msg, str):
raise ValueError(msg)
else:
raise ValueError(msg.encode('utf-8'))

等待 Python 代码级别的补丁(例如 6, future 包)几乎是不可能的,因为有问题的代码在 pythonrun.c 中的 C 代码级别,好像是 PyObject_Str(value)执行 unicode 字符串返回 null

关于python-2.7 - Python 2.7 异常不处理 python3 兼容代码中的 unicode ('<exception str() failed>' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46076279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com