Python Forum
TypeError: a bytes-like object is required, not 'str'. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: TypeError: a bytes-like object is required, not 'str'. (/thread-26008.html)



TypeError: a bytes-like object is required, not 'str'. - jacklee26 - Apr-18-2020

Do anyone know how to convert the byte to str. I used below code work on python2 but if I used python3 it will occur Error like this:
TypeError: a bytes-like object is required, not 'str'.

So I try to use stdout = stdout.decode("UTF-8"), but it will also pop error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa8 in position 16: invalid start byte

# -*- coding: utf-8 -*-
import telnetlib
import subprocess
import time


def Telnet_Check_reachability(ip):
    ping_count=3
    process = subprocess.Popen(['ping', ip, '-n', str(ping_count)],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    
    process.wait()
    stdout = process.stdout.read()
   
    print (type(stdout))
    print (stdout)
    if "TTL=" in stdout:
        #print "Server reachable"
        #successful = 1
        print("1 Server reachable ")
    else:
        #print "Server unreachable"
        successful = 0
        print("0 Server unreachable")
    #return successful
ip ="8.8.8.8"
new_IPv6 = Telnet_Check_reachability(ip)
#print(new_IPv6)



RE: TypeError: a bytes-like object is required, not 'str'. - buran - Apr-18-2020

Please, post full traceback you get, not just the last line, in error tags


RE: TypeError: a bytes-like object is required, not 'str'. - jacklee26 - Apr-18-2020

Error:
Traceback (most recent call last): File "ip_check.py", line 28, in <module> new_IPv6 = Telnet_Check_reachability(ip) File "ip_check.py", line 13, in Telnet_Check_reachability stdout = stdout.encode("UTF-8") AttributeError: 'bytes' object has no attribute 'encode'
adding decode
Error:
Traceback (most recent call last): File "ip_check.py", line 28, in <module> new_IPv6 = Telnet_Check_reachability(ip) File "ip_check.py", line 13, in Telnet_Check_reachability stdout = stdout.decode("UTF-8") UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa8 in position 16: invalid start byte



RE: TypeError: a bytes-like object is required, not 'str'. - ibreeden - Apr-18-2020

Adding "stdout = stdout.decode("UTF-8")" seems to be a bad choice. I would remove it.
Perhaps better to concentrate on the original message: "TypeError: a bytes-like object is required, not 'str'".
Please show us the complete message and the code where that error occurs.


RE: TypeError: a bytes-like object is required, not 'str'. - jacklee26 - Apr-18-2020

I change to stdout = stdout.decode("big5") and can work correct.

so python2 uses str, but python3 uses byte.
Python3 has to decode to convert byte to str. Why do we have to do that?