【发布时间】:2018-01-22 05:12:48
【问题描述】:
我认为这是非常基本的,但似乎甚至无法弄清楚如何向谷歌提出正确的问题。我正在使用 this python websocket client 进行一些 websocket 连接。让我们假设我正在使用类似于该页面的代码示例:
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() 只需要 2 个参数(给定 1 个)
如何将这些新参数传递给我的 on_open 函数?
【问题讨论】:
-
@cᴏʟᴅsᴘᴇᴇᴅ 是的,两者都有帮助,但我最终更喜欢你的
partial用法,我会接受那个。
标签: python python-2.7 function parameter-passing