我是python的新手,我不得不在python中编写我的第一个任务。我保证在完成这项工作后我将从内到外学习它,但我现在需要你的帮助。
我的代码目前看起来像这样:
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
是另一种方法。我想通过创建一个新方法来重写此代码,以便我可以传递message
,引用socket
,然后return
我从套接字收到的内容。
任何帮助?
谢谢:)
答案 0 :(得分:3)
猜测你想要的是什么:
def send_and_receive(message, socket):
socket.send(message)
return socket.recv(256) # number is timeout
然后将try:except:
放在此方法的调用上。
答案 1 :(得分:2)
一个简单的解决方案是
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
答案 2 :(得分:1)
您应该执行一个类来管理您的错误,并且该类需要扩展您用于comSocket实例的类,在您放置errorLog函数的类中。 像这样:
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
现在只用它来实现它的实例化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)
希望有帮助,你没有发布你的功能错误日志的内容,所以我把评论放在你应该放的地方。这是一种做事方式。希望有所帮助。