2017-08-14 90 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) 
相关问题