Python AttributeError:’str’对象没有属性’decode’

Python AttributeError: 'str' object has no attribute 'decode'

我正在开发一个关于python的项目,它允许与日志进行基本的TCP通信。但是正在接收的数据是以B前缀接收的。

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

1
2
3
4
5
6
7
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
eceiver.py"
, line 26, in receive
    print(data.decode('utf-8'))
AttributeError: 'str' object has no attribute 'decode'

服务器在python 3.6上运行,客户机在python 2.7上运行。

这是我的服务器代码:

Me.Py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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()`

P.P.P.Py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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()

和客户.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/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()时,传入的数据如下所示:

1
2
3
4
b'T'
b'e'
b's'
b't'

引用对类似问题的现有答案:

You are trying to decode an object that is already decoded. You have a str, there is no need to decode from UTF-8 anymore.

针对您的问题,这里有一个问题:

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

data = str(data)已经将数据转换成一个字符串,然后通过字符串使用data.decode(utf-8')再次对其进行解码。

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