简体   繁体   中英

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

Im working on a project on Python that allows basic TCP communications with logs. But the data that is being received is being received with ab prefix.

After many hours of troubleshooting other errors, I come down to this final error that always happens and I can't seem to fix. After doing some research for a few days, I found out that the b prefix is part of the data string and whenever I try to use print(data.decode()) or print(data.decode('utf-8') I get the error:

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'

The server is running on Python 3.6 and the client on Python 2.7

Here's my Server code:

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() 

And the 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()

Also, when I remove the .decode() the data incoming goes like this:

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

To quote from an existing answer to a similar problem:

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.

Specific to your question, here is the problem:

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

data = str(data) has already converted data to a string and then you're trying to decode it again using data.decode(utf-8') .

The solution is simple, simply remove the data = str(data) statement (or remove the decode statement and simply do print(data) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM