2011-07-12 79 views
2

我是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,然后return从套接字收到的信息。

任何帮助?

谢谢:)

+0

通过什么样的信息? – SingleNegationElimination

+0

'\ r \ r'是一条消息:)消息将是任意长度的字符串。 –

+0

http://docs.python.org/tutorial/controlflow.html#defining-functions – SingleNegationElimination

回答

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 
3

来猜测你想要什么:

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

然后把你的try:except:在你调用此方法。

+0

+1的简单答案。 –

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) 

希望,帮助,你不发表您的功能错误日志的内容,所以我发表了你应该把它放在哪里的评论。这是做事的一种方式。希望有所帮助。

+0

哦,你也可以使用装饰器,让我知道如果我的建议帮助或我们可以尝试别的。 –