2011-07-12 104 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

哦,你也可以使用裝飾器,讓我知道如果我的建議幫助或我們可以嘗試別的。 –