当前位置:   article > 正文

Python a bytes-like object is required, not 'str'_a bites-like object is required not str

a bites-like object is required not str

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/twisted/python/log.py", line 103, in callWithLogger
    return callWithContext({"system": lp}, func, *args, **kw)
  File "/usr/local/lib/python3.5/dist-packages/twisted/python/log.py", line 86, in callWithContext
    return context.call({ILogContext: newCtx}, func, *args, **kw)
  File "/usr/local/lib/python3.5/dist-packages/twisted/python/context.py", line 122, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "/usr/local/lib/python3.5/dist-packages/twisted/python/context.py", line 85, in callWithContext
    return func(*args,**kw)
--- <exception caught here> ---
  File "/usr/local/lib/python3.5/dist-packages/twisted/internet/posixbase.py", line 614, in _doReadOrWrite
    why = selectable.doRead()
  File "/usr/local/lib/python3.5/dist-packages/twisted/internet/tcp.py", line 243, in doRead
    return self._dataReceived(data)
  File "/usr/local/lib/python3.5/dist-packages/twisted/internet/tcp.py", line 249, in _dataReceived
    rval = self.protocol.dataReceived(data)
  File "main.py", line 32, in dataReceived
    data = redis_protocol.decode(rcvdata)  # data类型:list
  File "/usr/local/lib/python3.5/dist-packages/redis_protocol/protocol.py", line 22, in decode
    processed, index = 0, data.find(DELIMITER)
builtins.TypeError: a bytes-like object is required, not 'str'

python2转python3遇到的问题

看源码

  1. data = redis_protocol.decode(rcvdata)
  2. command = " ".join(redis_protocol.decode(rcvdata))

rcvdata在python2中为str类型,但是在python3中为bytes类型,所以我们要转换参数类型

  1. data = redis_protocol.decode(rcvdata.decode()) # data类型:list
  2. command = " ".join(redis_protocol.decode(rcvdata.decode())) # command类型:string

 

转换方法 

从str到bytes:调用方法encode().

从bytes到str:调用方法decode().

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/215929
推荐阅读
相关标签
  

闽ICP备14008679号