Jér*_*ôme 8 python unicode pyqt python-2.7
我正在用Unicode字符串编写Python 2代码,导入unicode_literals并且我遇到了引发异常的问题.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
raise Exception('Tést')
Run Code Online (Sandbox Code Playgroud)
执行此操作时,"Tést"字符串将从终端上剥离.
我可以解决这个问题
raise Exception('Tést'.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
我宁愿找到一个全局解决方案而不是在所有raise Exception语句中都这样做.
(因为我tr()在异常消息中使用PyQt的函数,必须处理特殊字符,在编码时我不知道是否encode('utf-8')有必要.)
更差.有时,我想捕获一个Exception,获取它的消息,然后引发一个新的Exception,将一个基本字符串与第一个Exception字符串连接起来.
我必须这样做:
try:
raise TypeError('Tést'.encode('utf-8'))
except Exception as e:
raise Exception('Exception: {}'.format(str(e).decode('utf-8')).encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
但我真的希望它可以不那么麻烦(这个例子甚至不包括self.tr()调用).
有没有更简单的方法?
(作为一个附带问题,使用Python3的事情更简单吗?Exception可以使用unicode字符串吗?)
Jér*_*ôme 12
感谢问题下面的评论,我想出了这个.
我们的想法是使用自定义的Exception子类.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class MyException(Exception):
def __init__(self, message):
if isinstance(message, unicode):
super(MyException, self).__init__(message.encode('utf-8'))
self.message = message
elif isinstance(message, str):
super(MyException, self).__init__(message)
self.message = message.decode('utf-8')
# This shouldn't happen...
else:
raise TypeError
def __unicode__(self):
return self.message
class MySubException(MyException):
pass
try:
raise MyException('Tést')
except MyException as e:
print(e.message)
raise MySubException('SubException: {}'.format(e))
Run Code Online (Sandbox Code Playgroud)