Reputation: 4712
I am new to python and I am having to code my 1st task in python. I promise that I will learn it inside out after I finish this but I need your help now.
My code is currently looks like this:
comSocket.send("\r")
sleep(1)
comSocket.send("\r")
sleep(2)
comSocket.settimeout(8)
try:
comSocket.recv(256)
except socket.timeout:
errorLog("[COM. ERROR] Station took too long to reply. \n")
comSocket.shutdown(1)
comSocket.close()
sys.exit(0)
comSocket.send("\r\r")
sleep(2)
comSocket.settimeout(8)
try:
comSocket.recv(256)
except socket.timeout:
errorLog("[COM. ERROR] Station took too long to reply. \n")
comSocket.shutdown(1)
comSocket.close()
sys.exit(0)
errorLog
is another method. I want to rewrite this code by making a new method so that I can pass the message
, reference to the socket
and then return
what I receive from the socket.
Any help?
Thank you :)
Upvotes: 2
Views: 4381
Reputation: 2368
You should do a class to manage your errors and that class needs to extend the one you are using for the instance of comSocket, inside that class you put your errorLog function. Something like this:
class ComunicationSocket(socket):
def errorLog(self, message):
# in this case, self it's an instance of your object comSocket,
# therefore your "reference"
# place the content of errorLog function
return True # Here you return what you received from socket
Now with this only what you have to do its instantiate ComunicationSocket:
comSocket = ComunicationSocket()
try:
comSocket.recv(256)
except socket.timeout:
# Uses the instance of comSocket to log the error
comSocket.errorLog("[COM. ERROR] Station took too long to reply. \n")
comSocket.shutdown(1)
comSocket.close()
sys.exit(0)
Hope that helped, you didn't post the content of your function error log, so I placed a comment where you should put it. This is one way of doing things. Hope that helps.
Upvotes: 1
Reputation: 4712
A simple solution would be
def socketCom(comSocket, length, message, time):
comSocket.send(message)
comSocket.settimeout(8)
if (time != 0):
sleep(time)
try:
rawData = comSocket.recv(length)
except socket.timeout:
errorLog("[COM. ERROR] Station took too long to reply. \n")
comSocket.shutdown(1)
comSocket.close()
sys.exit(0)
return rawData
Upvotes: 2
Reputation: 6166
A guess at what you're trying for:
def send_and_receive(message, socket):
socket.send(message)
return socket.recv(256) # number is timeout
then put your try:except:
around your call to this method.
Upvotes: 3