gpt4 book ai didi

python - 如何将类似字符串的字节转换为普通字节?

转载 作者:行者123 更新时间:2023-12-01 00:38:36 25 4
gpt4 key购买 nike

我在使用 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'

编辑1

@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'

编辑2

@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* 中得到字符串化字节。

有两种方法可以解决这个问题:

  1. 通过异常的 args 元组访问原始字节:

msg = e.args[0].decode()

  • 使用ast.literal_eval转换字符串化异常:
  • 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/

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