Python:通过引用传递套接字

2024-05-18 07:13:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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,然后{}从套接字接收到的内容。在

有什么帮助吗?在

谢谢:)


Tags: 代码comsendtimeoutsleeperrorsocketerrorlog
3条回答

猜猜你想干什么:

def send_and_receive(message, socket):
    socket.send(message)
    return socket.recv(256) # number is timeout

然后将您的try:except:放在对该方法的调用周围。在

你应该做一个类来管理你的错误,这个类需要扩展你在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

现在,您只需执行它的实例化通信套接字:

^{pr2}$

希望这有帮助,你没有发布你的函数错误日志的内容,所以我在你应该把它放在的地方。这是做事的一种方式。希望有帮助。在

一个简单的解决方案是

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

相关问题 更多 >