作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在使用 imapclient 进行异常处理时遇到问题-图书馆。
我尝试像这样处理 LoginError:
source = IMAPClient(host=args.source_server, port=args.source_port, ssl=not args.source_no_ssl)
try:
print('Login source...'.format(args.source_user), end='', flush=False)
source.login(args.source_user, args.source_pass)
print('OK')
except exceptions.LoginError as e:
print('ERROR: {}'.format(e))
exit()
如果出现异常,我有这个:
Login source...ERROR: b'Invalid login'
我认为问题是,format
正在调用异常对象的__str__()
方法,并且不尝试解码。
所以主要问题是谁可以转换这个字符串
"b'Invalid login'"
像这样的普通字节对象?
b'Invalid login'
@lenik如果我像这样使用e.message.decode()
:
try:
print('Login source...'.format(args.source_user), end='', flush=False)
source.login(args.source_user, args.source_pass)
print('OK')
except exceptions.LoginError as e:
print('ERROR: {}'.format(e.message.decode()))
exit()
我有一个属性错误:
AttributeError: 'LoginError' object has no attribute 'message'
@snakecharmerb
try:
print('Login source...'.format(args.source_user), end='', flush=False)
source.login(args.source_user, args.source_pass)
print('OK')
except exceptions.LoginError as e:
print('ERROR: {}'.format(e.args[0].decode()))
exit()
AttributeError: 'str' object has no attribute 'decode'
最佳答案
imapclient
的登录方法看起来像 this :
def login(self, username, password):
"""Login using *username* and *password*, returning the
server response.
"""
try:
rv = self._command_and_check(
'login',
to_unicode(username),
to_unicode(password),
unpack=True,
)
except exceptions.IMAPClientError as e:
raise exceptions.LoginError(str(e))
logger.info('Logged in as %s', username)
return rv
我们可以看到它在 IMAPClientError
上调用 str
,因此如果 IMAPClientError
是使用 bytes
实例创建的作为其参数,那么我们最终会在 LoginError
* 中得到字符串化字节。
有两种方法可以解决这个问题:
args
元组访问原始字节:msg = e.args[0].decode()
msg = ast.literal_eval(str(e)).decode()
在这两种方法中,我认为 (1) 在这种特定情况下更好,但当您有字符串化字节时,(2) 更普遍适用。
<小时/>*查看 imaplib 的历史在 github 上的模块中,看起来好像它更改为在从 Python 3.5 中的验证命令引发错误之前显式解码错误消息。因此,另一个解决方案可能是升级到 Python 3.5+。
关于python - 如何将类似字符串的字节转换为普通字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543488/
我是一名优秀的程序员,十分优秀!