2017-08-14 89 views
1

我認爲這是非常基本的,但似乎無法弄清楚如何向google提出正確的問題。我使用this python websocket client來建立一些websocket連接。讓我們只是假設我用類似網頁的代碼示例:將更多參數傳遞給這種類型的python函數

import websocket 
import thread 
import time 

def on_message(ws, message): 
    print(message) 

def on_error(ws, error): 
    print(error) 

def on_close(ws): 
    print("### closed ###") 

def on_open(ws): 
    def run(*args): 
     ws.send("Hello") 
     time.sleep(1) 
     ws.close() 
     print("thread terminating...") 
    thread.start_new_thread(run,()) 


if __name__ == "__main__": 
    websocket.enableTrace(True) 
    ws = websocket.WebSocketApp("ws://echo.websocket.org/", 
           on_message = on_message, 
           on_error = on_error, 
           on_close = on_close) 
    ws.on_open = on_open 
    ws.run_forever() 

所以我試圖做的是增加更多的參數給on_open功能,這樣的事情:

def on_open(ws, more_arg): 
    def run(*args): 
     ws.send("Hello %s" % more_arg) 
     time.sleep(1) 
     ws.close() 
     print("thread terminating...") 
    thread.start_new_thread(run,()) 

但我無法弄清楚如何通過這些參數,所以我在主線程嘗試:

ws.on_open = on_open("this new arg") 

,但我得到的錯誤:

TypeError: on_open() takes exactly 2 arguments (1 given)

我該如何將這些新的參數傳遞給我的on_open函數?

+0

@cᴏʟᴅsᴘᴇᴇᴅ是既幫助了,但我最終喜歡你的'partial'使用更好,我會接受的。 –

回答

2

請記住,您需要指定一個回調。而是調用一個函數並將返回值傳遞給ws,這是不正確的。

您可以使用functools.partial討好的功能,高階一個:

from functools import partial 

func = partial(on_open, "this new arg") 
ws.on_open = func 

當調用func,它會調用on_open的第一個參數爲"this new arg",然後傳遞給func任何其他參數。有關更多詳細信息,請參閱文檔鏈接中的partial的實現。

+0

謝謝是的術語「回調」是我認爲我是空白。感謝這一點,儘管我不得不說Danial Sanchez建議的lambda技術看起來很蟒蛇。 –

+1

@jeffery_the_wind是的......他們都一樣。就個人而言,我不喜歡lambdas :) –

1

可以使用lambda包呼叫:

ws.on_open = lambda *x: on_open("this new arg", *x) 
相關問題