Python AttributeError:“ str”对象没有属性“ decode”

时间:2018-06-22 02:04:44

标签: python

我正在Python上进行一个项目,该项目允许使用日志进行基本的TCP通信。但是正在接收的数据正以b前缀接收。

在对其他错误进行了数小时的故障排除之后,我得出了这个总是会发生的最终错误,但似乎无法修复。经过几天的研究,我发现b前缀是数据字符串的一部分,每当我尝试使用print(data.decode())或print(data.decode('utf-8')得到错误:

2018-06-21 21:17:38,801 STCP STOPPED DUE TO ERROR ON main.py, main()
Traceback (most recent call last):
  File "main.py", line 14, in main
    receiver.receive()
  File "D:\SecureNetworks\SecureTCP\receiver.py", line 26, in receive
    print(data.decode('utf-8'))
AttributeError: 'str' object has no attribute 'decode'

服务器在Python 3.6上运行,客户端在Python 2.7上运行

这是我的服务器代码:

main.py

import logging
import receiver
import config
logger = logging.getLogger(config.log)
hdlr = logging.FileHandler(str(config.log) + '.log')
formatter = logging.Formatter('%(asctime)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)

def main():
    try:
        logger.info("STCP has started.")
        receiver.receive()
    except ConnectionResetError:
        print("Client has disconnected.")
        logger.info("Client has disconnected.")
    except:
        print("STCP STOPPED DUE TO ERROR ON main.py, main()")
        logger.exception("STCP STOPPED DUE TO ERROR ON main.py, main()")

if __name__ == '__main__':
    main()`

receiver.py

import socket
import logging
import config
logger = logging.getLogger(config.log)
hdlr = logging.FileHandler(str(config.log) + '.log')
formatter = logging.Formatter('%(asctime)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)

TCP_IP = config.host
TCP_PORT = config.port
BUFFER_SIZE = config.buffersize

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logger.info("STCP receiver has began on " + str(TCP_IP) + ":" +  str(TCP_PORT))
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
logger.info("Connection accepted from " + str(addr))
def receive():
    while 1:
        data = conn.recv(BUFFER_SIZE)
        if not data: break
        data = str(data)
        print(data.decode('utf-8'))
        conn.send(bytes(data, 'UTF-8'))
        logger.info(data)
    conn.close() 

还有client.py

#!/usr/bin/env python
import socket
import getpass

TCP_IP = '192.168.0.5'
TCP_PORT = 6430
BUFFER_SIZE = 1
MESSAGE = "Test"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

此外,当我删除.decode()时,传入的数据如下所示:

b'T'
b'e'
b's'
b't'

1 个答案:

答案 0 :(得分:0)

要引用existing answer中的类似问题:

  

您正在尝试解码已解码的对象。您有了一个str,就不再需要从UTF-8解码。

特定于您的问题,这是问题所在:

    data = str(data)
    print(data.decode('utf-8'))

data = str(data)已经将数据转换为字符串,然后您就可以使用data.decode(utf-8')再次将其解码。

解决方案很简单,只需删除data = str(data)语句(或删除解码语句并仅执行print(data)