Python buf.find('***identified***') >= 0: TypeError: a bytes-like object is required, not 'str'












0















I am trying to rewrite the following Python 2 code to Python 3. Inside the repository, there is a pyclient.py file. I changed it to the following



#!/usr/bin/env python
'''
Created on Apr 4, 2012

@author: lanquarden
'''
import sys
import argparse
import socket
import driver

if __name__ == '__main__':
pass

# Configure the argument parser
parser = argparse.ArgumentParser(description = 'Python client to connect to the TORCS SCRC server.')

parser.add_argument('--host', action='store', dest='host_ip', default='localhost',
help='Host IP address (default: localhost)')
parser.add_argument('--port', action='store', type=int, dest='host_port', default=3001,
help='Host port number (default: 3001)')
parser.add_argument('--id', action='store', dest='id', default='SCR',
help='Bot ID (default: SCR)')
parser.add_argument('--maxEpisodes', action='store', dest='max_episodes', type=int, default=1,
help='Maximum number of learning episodes (default: 1)')
parser.add_argument('--maxSteps', action='store', dest='max_steps', type=int, default=0,
help='Maximum number of steps (default: 0)')
parser.add_argument('--track', action='store', dest='track', default=None,
help='Name of the track')
parser.add_argument('--stage', action='store', dest='stage', type=int, default=3,
help='Stage (0 - Warm-Up, 1 - Qualifying, 2 - Race, 3 - Unknown)')

arguments = parser.parse_args()

# Print summary
print('Connecting to server host ip:', arguments.host_ip, '@ port:', arguments.host_port)
print('Bot ID:', arguments.id)
print('Maximum episodes:', arguments.max_episodes)
print('Maximum steps:', arguments.max_steps)
print('Track:', arguments.track)
print('Stage:', arguments.stage)
print('*********************************************')

try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error as msg:
print('Could not make a socket.')
sys.exit(-1)

# one second timeout
sock.settimeout(1.0)

shutdownClient = False
curEpisode = 0

verbose = False

d = driver.Driver(arguments.stage)

while not shutdownClient:
while True:
print('Sending id to server: ', arguments.id)
buf = arguments.id + d.init()
print('Sending init string to server:', buf)

try:
sock.sendto(buf.encode(), (arguments.host_ip, arguments.host_port))
except socket.error as msg:
print('Failed to send data...Exiting...')
sys.exit(-1)

try:
buf, addr = sock.recvfrom(1000)
except socket.error as msg:
print('didn't get response from server...')

if buf.find('***identified***') >= 0:
print('Received: ', buf)
break

currentStep = 0

while True:
# wait for an answer from server
buf = None
try:
buf, addr = sock.recvfrom(1000)
except socket.error as msg:
print('didn't get response from server...')

if verbose:
print('Received: ', buf)

if buf != None and buf.find('***shutdown***') >= 0:
d.onShutDown()
shutdownClient = True
print('Client Shutdown')
break

if buf != None and buf.find('***restart***') >= 0:
d.onRestart()
print('Client Restart')
break

currentStep += 1
if currentStep != arguments.max_steps:
if buf != None:
buf = d.drive(buf)
else:
buf = '(meta 1)'

if verbose:
print('Sending: ', buf)

if buf != None:
try:
sock.sendto(buf.encode(), (arguments.host_ip, arguments.host_port))
except socket.error as msg:
print('Failed to send data...Exiting...')
sys.exit(-1)

curEpisode += 1

if curEpisode == arguments.max_episodes:
shutdownClient = True


sock.close()


I also changed the msgParser.py



'''
Created on Apr 5, 2012

@author: lanquarden
'''

class MsgParser(object):
'''
A parser for received UDP messages and building UDP messages
'''
def __init__(self):
'''Constructor'''

def parse(self, str_sensors):
'''Return a dictionary with tags and values from the UDP message'''
sensors = {}

b_open = str_sensors.find('(')

while b_open >= 0:
b_close = str_sensors.find(')', b_open)
if b_close >= 0:
substr = str_sensors[b_open + 1: b_close]
items = substr.split()
if len(items) < 2:
print('Problem parsing substring: ', substr)
else:
value =
for i in range(1,len(items)):
value.append(items[i])
sensors[items[0]] = value
b_open = str_sensors.find('(', b_close)
else:
print('Problem parsing sensor string: "', str_sensors)
return None

return sensors

def stringify(self, dictionary):
'''Build an UDP message from a dictionary'''
msg = ''

for key, value in dictionary.items():
if value != None and value[0] != None:
msg += '(' + key
for val in value:
msg += ' ' + str(val)
msg += ')'

return msg



Question: But when I start TORCS and want to run the module pyclient.py I get
the following error buf.find('***identified***') >= 0: TypeError: a
bytes-like object is required, not 'str'
. I know my code is not a
minimal working example but I don't know how to abstract the problem
such that I can reproduce the error. I already tried buf.find('***identified***').encode() but that did not solve the issue.











share|improve this question























  • try buf.find(bytes('***identified***', 'utf-8'))

    – Carlos Gonzalez
    Nov 16 '18 at 11:27













  • @CarlosGonzalez Thank you for the hint! I got rid of all the errors. Now another error appeared.

    – MrYouMath
    Nov 16 '18 at 12:24
















0















I am trying to rewrite the following Python 2 code to Python 3. Inside the repository, there is a pyclient.py file. I changed it to the following



#!/usr/bin/env python
'''
Created on Apr 4, 2012

@author: lanquarden
'''
import sys
import argparse
import socket
import driver

if __name__ == '__main__':
pass

# Configure the argument parser
parser = argparse.ArgumentParser(description = 'Python client to connect to the TORCS SCRC server.')

parser.add_argument('--host', action='store', dest='host_ip', default='localhost',
help='Host IP address (default: localhost)')
parser.add_argument('--port', action='store', type=int, dest='host_port', default=3001,
help='Host port number (default: 3001)')
parser.add_argument('--id', action='store', dest='id', default='SCR',
help='Bot ID (default: SCR)')
parser.add_argument('--maxEpisodes', action='store', dest='max_episodes', type=int, default=1,
help='Maximum number of learning episodes (default: 1)')
parser.add_argument('--maxSteps', action='store', dest='max_steps', type=int, default=0,
help='Maximum number of steps (default: 0)')
parser.add_argument('--track', action='store', dest='track', default=None,
help='Name of the track')
parser.add_argument('--stage', action='store', dest='stage', type=int, default=3,
help='Stage (0 - Warm-Up, 1 - Qualifying, 2 - Race, 3 - Unknown)')

arguments = parser.parse_args()

# Print summary
print('Connecting to server host ip:', arguments.host_ip, '@ port:', arguments.host_port)
print('Bot ID:', arguments.id)
print('Maximum episodes:', arguments.max_episodes)
print('Maximum steps:', arguments.max_steps)
print('Track:', arguments.track)
print('Stage:', arguments.stage)
print('*********************************************')

try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error as msg:
print('Could not make a socket.')
sys.exit(-1)

# one second timeout
sock.settimeout(1.0)

shutdownClient = False
curEpisode = 0

verbose = False

d = driver.Driver(arguments.stage)

while not shutdownClient:
while True:
print('Sending id to server: ', arguments.id)
buf = arguments.id + d.init()
print('Sending init string to server:', buf)

try:
sock.sendto(buf.encode(), (arguments.host_ip, arguments.host_port))
except socket.error as msg:
print('Failed to send data...Exiting...')
sys.exit(-1)

try:
buf, addr = sock.recvfrom(1000)
except socket.error as msg:
print('didn't get response from server...')

if buf.find('***identified***') >= 0:
print('Received: ', buf)
break

currentStep = 0

while True:
# wait for an answer from server
buf = None
try:
buf, addr = sock.recvfrom(1000)
except socket.error as msg:
print('didn't get response from server...')

if verbose:
print('Received: ', buf)

if buf != None and buf.find('***shutdown***') >= 0:
d.onShutDown()
shutdownClient = True
print('Client Shutdown')
break

if buf != None and buf.find('***restart***') >= 0:
d.onRestart()
print('Client Restart')
break

currentStep += 1
if currentStep != arguments.max_steps:
if buf != None:
buf = d.drive(buf)
else:
buf = '(meta 1)'

if verbose:
print('Sending: ', buf)

if buf != None:
try:
sock.sendto(buf.encode(), (arguments.host_ip, arguments.host_port))
except socket.error as msg:
print('Failed to send data...Exiting...')
sys.exit(-1)

curEpisode += 1

if curEpisode == arguments.max_episodes:
shutdownClient = True


sock.close()


I also changed the msgParser.py



'''
Created on Apr 5, 2012

@author: lanquarden
'''

class MsgParser(object):
'''
A parser for received UDP messages and building UDP messages
'''
def __init__(self):
'''Constructor'''

def parse(self, str_sensors):
'''Return a dictionary with tags and values from the UDP message'''
sensors = {}

b_open = str_sensors.find('(')

while b_open >= 0:
b_close = str_sensors.find(')', b_open)
if b_close >= 0:
substr = str_sensors[b_open + 1: b_close]
items = substr.split()
if len(items) < 2:
print('Problem parsing substring: ', substr)
else:
value =
for i in range(1,len(items)):
value.append(items[i])
sensors[items[0]] = value
b_open = str_sensors.find('(', b_close)
else:
print('Problem parsing sensor string: "', str_sensors)
return None

return sensors

def stringify(self, dictionary):
'''Build an UDP message from a dictionary'''
msg = ''

for key, value in dictionary.items():
if value != None and value[0] != None:
msg += '(' + key
for val in value:
msg += ' ' + str(val)
msg += ')'

return msg



Question: But when I start TORCS and want to run the module pyclient.py I get
the following error buf.find('***identified***') >= 0: TypeError: a
bytes-like object is required, not 'str'
. I know my code is not a
minimal working example but I don't know how to abstract the problem
such that I can reproduce the error. I already tried buf.find('***identified***').encode() but that did not solve the issue.











share|improve this question























  • try buf.find(bytes('***identified***', 'utf-8'))

    – Carlos Gonzalez
    Nov 16 '18 at 11:27













  • @CarlosGonzalez Thank you for the hint! I got rid of all the errors. Now another error appeared.

    – MrYouMath
    Nov 16 '18 at 12:24














0












0








0








I am trying to rewrite the following Python 2 code to Python 3. Inside the repository, there is a pyclient.py file. I changed it to the following



#!/usr/bin/env python
'''
Created on Apr 4, 2012

@author: lanquarden
'''
import sys
import argparse
import socket
import driver

if __name__ == '__main__':
pass

# Configure the argument parser
parser = argparse.ArgumentParser(description = 'Python client to connect to the TORCS SCRC server.')

parser.add_argument('--host', action='store', dest='host_ip', default='localhost',
help='Host IP address (default: localhost)')
parser.add_argument('--port', action='store', type=int, dest='host_port', default=3001,
help='Host port number (default: 3001)')
parser.add_argument('--id', action='store', dest='id', default='SCR',
help='Bot ID (default: SCR)')
parser.add_argument('--maxEpisodes', action='store', dest='max_episodes', type=int, default=1,
help='Maximum number of learning episodes (default: 1)')
parser.add_argument('--maxSteps', action='store', dest='max_steps', type=int, default=0,
help='Maximum number of steps (default: 0)')
parser.add_argument('--track', action='store', dest='track', default=None,
help='Name of the track')
parser.add_argument('--stage', action='store', dest='stage', type=int, default=3,
help='Stage (0 - Warm-Up, 1 - Qualifying, 2 - Race, 3 - Unknown)')

arguments = parser.parse_args()

# Print summary
print('Connecting to server host ip:', arguments.host_ip, '@ port:', arguments.host_port)
print('Bot ID:', arguments.id)
print('Maximum episodes:', arguments.max_episodes)
print('Maximum steps:', arguments.max_steps)
print('Track:', arguments.track)
print('Stage:', arguments.stage)
print('*********************************************')

try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error as msg:
print('Could not make a socket.')
sys.exit(-1)

# one second timeout
sock.settimeout(1.0)

shutdownClient = False
curEpisode = 0

verbose = False

d = driver.Driver(arguments.stage)

while not shutdownClient:
while True:
print('Sending id to server: ', arguments.id)
buf = arguments.id + d.init()
print('Sending init string to server:', buf)

try:
sock.sendto(buf.encode(), (arguments.host_ip, arguments.host_port))
except socket.error as msg:
print('Failed to send data...Exiting...')
sys.exit(-1)

try:
buf, addr = sock.recvfrom(1000)
except socket.error as msg:
print('didn't get response from server...')

if buf.find('***identified***') >= 0:
print('Received: ', buf)
break

currentStep = 0

while True:
# wait for an answer from server
buf = None
try:
buf, addr = sock.recvfrom(1000)
except socket.error as msg:
print('didn't get response from server...')

if verbose:
print('Received: ', buf)

if buf != None and buf.find('***shutdown***') >= 0:
d.onShutDown()
shutdownClient = True
print('Client Shutdown')
break

if buf != None and buf.find('***restart***') >= 0:
d.onRestart()
print('Client Restart')
break

currentStep += 1
if currentStep != arguments.max_steps:
if buf != None:
buf = d.drive(buf)
else:
buf = '(meta 1)'

if verbose:
print('Sending: ', buf)

if buf != None:
try:
sock.sendto(buf.encode(), (arguments.host_ip, arguments.host_port))
except socket.error as msg:
print('Failed to send data...Exiting...')
sys.exit(-1)

curEpisode += 1

if curEpisode == arguments.max_episodes:
shutdownClient = True


sock.close()


I also changed the msgParser.py



'''
Created on Apr 5, 2012

@author: lanquarden
'''

class MsgParser(object):
'''
A parser for received UDP messages and building UDP messages
'''
def __init__(self):
'''Constructor'''

def parse(self, str_sensors):
'''Return a dictionary with tags and values from the UDP message'''
sensors = {}

b_open = str_sensors.find('(')

while b_open >= 0:
b_close = str_sensors.find(')', b_open)
if b_close >= 0:
substr = str_sensors[b_open + 1: b_close]
items = substr.split()
if len(items) < 2:
print('Problem parsing substring: ', substr)
else:
value =
for i in range(1,len(items)):
value.append(items[i])
sensors[items[0]] = value
b_open = str_sensors.find('(', b_close)
else:
print('Problem parsing sensor string: "', str_sensors)
return None

return sensors

def stringify(self, dictionary):
'''Build an UDP message from a dictionary'''
msg = ''

for key, value in dictionary.items():
if value != None and value[0] != None:
msg += '(' + key
for val in value:
msg += ' ' + str(val)
msg += ')'

return msg



Question: But when I start TORCS and want to run the module pyclient.py I get
the following error buf.find('***identified***') >= 0: TypeError: a
bytes-like object is required, not 'str'
. I know my code is not a
minimal working example but I don't know how to abstract the problem
such that I can reproduce the error. I already tried buf.find('***identified***').encode() but that did not solve the issue.











share|improve this question














I am trying to rewrite the following Python 2 code to Python 3. Inside the repository, there is a pyclient.py file. I changed it to the following



#!/usr/bin/env python
'''
Created on Apr 4, 2012

@author: lanquarden
'''
import sys
import argparse
import socket
import driver

if __name__ == '__main__':
pass

# Configure the argument parser
parser = argparse.ArgumentParser(description = 'Python client to connect to the TORCS SCRC server.')

parser.add_argument('--host', action='store', dest='host_ip', default='localhost',
help='Host IP address (default: localhost)')
parser.add_argument('--port', action='store', type=int, dest='host_port', default=3001,
help='Host port number (default: 3001)')
parser.add_argument('--id', action='store', dest='id', default='SCR',
help='Bot ID (default: SCR)')
parser.add_argument('--maxEpisodes', action='store', dest='max_episodes', type=int, default=1,
help='Maximum number of learning episodes (default: 1)')
parser.add_argument('--maxSteps', action='store', dest='max_steps', type=int, default=0,
help='Maximum number of steps (default: 0)')
parser.add_argument('--track', action='store', dest='track', default=None,
help='Name of the track')
parser.add_argument('--stage', action='store', dest='stage', type=int, default=3,
help='Stage (0 - Warm-Up, 1 - Qualifying, 2 - Race, 3 - Unknown)')

arguments = parser.parse_args()

# Print summary
print('Connecting to server host ip:', arguments.host_ip, '@ port:', arguments.host_port)
print('Bot ID:', arguments.id)
print('Maximum episodes:', arguments.max_episodes)
print('Maximum steps:', arguments.max_steps)
print('Track:', arguments.track)
print('Stage:', arguments.stage)
print('*********************************************')

try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error as msg:
print('Could not make a socket.')
sys.exit(-1)

# one second timeout
sock.settimeout(1.0)

shutdownClient = False
curEpisode = 0

verbose = False

d = driver.Driver(arguments.stage)

while not shutdownClient:
while True:
print('Sending id to server: ', arguments.id)
buf = arguments.id + d.init()
print('Sending init string to server:', buf)

try:
sock.sendto(buf.encode(), (arguments.host_ip, arguments.host_port))
except socket.error as msg:
print('Failed to send data...Exiting...')
sys.exit(-1)

try:
buf, addr = sock.recvfrom(1000)
except socket.error as msg:
print('didn't get response from server...')

if buf.find('***identified***') >= 0:
print('Received: ', buf)
break

currentStep = 0

while True:
# wait for an answer from server
buf = None
try:
buf, addr = sock.recvfrom(1000)
except socket.error as msg:
print('didn't get response from server...')

if verbose:
print('Received: ', buf)

if buf != None and buf.find('***shutdown***') >= 0:
d.onShutDown()
shutdownClient = True
print('Client Shutdown')
break

if buf != None and buf.find('***restart***') >= 0:
d.onRestart()
print('Client Restart')
break

currentStep += 1
if currentStep != arguments.max_steps:
if buf != None:
buf = d.drive(buf)
else:
buf = '(meta 1)'

if verbose:
print('Sending: ', buf)

if buf != None:
try:
sock.sendto(buf.encode(), (arguments.host_ip, arguments.host_port))
except socket.error as msg:
print('Failed to send data...Exiting...')
sys.exit(-1)

curEpisode += 1

if curEpisode == arguments.max_episodes:
shutdownClient = True


sock.close()


I also changed the msgParser.py



'''
Created on Apr 5, 2012

@author: lanquarden
'''

class MsgParser(object):
'''
A parser for received UDP messages and building UDP messages
'''
def __init__(self):
'''Constructor'''

def parse(self, str_sensors):
'''Return a dictionary with tags and values from the UDP message'''
sensors = {}

b_open = str_sensors.find('(')

while b_open >= 0:
b_close = str_sensors.find(')', b_open)
if b_close >= 0:
substr = str_sensors[b_open + 1: b_close]
items = substr.split()
if len(items) < 2:
print('Problem parsing substring: ', substr)
else:
value =
for i in range(1,len(items)):
value.append(items[i])
sensors[items[0]] = value
b_open = str_sensors.find('(', b_close)
else:
print('Problem parsing sensor string: "', str_sensors)
return None

return sensors

def stringify(self, dictionary):
'''Build an UDP message from a dictionary'''
msg = ''

for key, value in dictionary.items():
if value != None and value[0] != None:
msg += '(' + key
for val in value:
msg += ' ' + str(val)
msg += ')'

return msg



Question: But when I start TORCS and want to run the module pyclient.py I get
the following error buf.find('***identified***') >= 0: TypeError: a
bytes-like object is required, not 'str'
. I know my code is not a
minimal working example but I don't know how to abstract the problem
such that I can reproduce the error. I already tried buf.find('***identified***').encode() but that did not solve the issue.








python-3.x python-2.7






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 10:48









MrYouMathMrYouMath

11215




11215













  • try buf.find(bytes('***identified***', 'utf-8'))

    – Carlos Gonzalez
    Nov 16 '18 at 11:27













  • @CarlosGonzalez Thank you for the hint! I got rid of all the errors. Now another error appeared.

    – MrYouMath
    Nov 16 '18 at 12:24



















  • try buf.find(bytes('***identified***', 'utf-8'))

    – Carlos Gonzalez
    Nov 16 '18 at 11:27













  • @CarlosGonzalez Thank you for the hint! I got rid of all the errors. Now another error appeared.

    – MrYouMath
    Nov 16 '18 at 12:24

















try buf.find(bytes('***identified***', 'utf-8'))

– Carlos Gonzalez
Nov 16 '18 at 11:27







try buf.find(bytes('***identified***', 'utf-8'))

– Carlos Gonzalez
Nov 16 '18 at 11:27















@CarlosGonzalez Thank you for the hint! I got rid of all the errors. Now another error appeared.

– MrYouMath
Nov 16 '18 at 12:24





@CarlosGonzalez Thank you for the hint! I got rid of all the errors. Now another error appeared.

– MrYouMath
Nov 16 '18 at 12:24












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53336322%2fpython-buf-findidentified-0-typeerror-a-bytes-like-object-is-requ%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53336322%2fpython-buf-findidentified-0-typeerror-a-bytes-like-object-is-requ%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Xamarin.iOS Cant Deploy on Iphone

Glorious Revolution

Dulmage-Mendelsohn matrix decomposition in Python