Python:按引用传递套接字

2 投票
3 回答
4151 浏览
提问于 2025-04-16 21:21

我刚开始学习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是另一个方法。我想重写这段代码,创建一个新方法,这样我就可以传入messagesocket的引用,然后return我从socket收到的内容。

有人能帮帮我吗?

谢谢你们 :)

3 个回答

1

你应该创建一个类来管理你的错误,这个类需要继承你正在使用的 comSocket 实例。在这个类里面,你可以放入你的错误记录函数。大概是这样的:

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)

希望这对你有帮助。你没有贴出你的错误记录函数的内容,所以我在你应该放它的地方加了个注释。这只是一种做法。希望能帮到你。

3

我猜你想要的效果是这样的:

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

然后在你调用这个方法的时候,把你的 try:except: 代码包裹起来。

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

撰写回答