相关疑难解决方法(0)

将更多参数传递给这种类型的 python 函数

我认为这是非常基本的,但似乎无法弄清楚如何向谷歌提出正确的问题。我正在使用这个 python websocket 客户端来建立一些 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()
Run Code Online (Sandbox Code Playgroud)

所以我想要做的是向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, ())
Run Code Online (Sandbox Code Playgroud)

但我不知道如何传递这些参数,所以我在主线程中尝试:

ws.on_open = …
Run Code Online (Sandbox Code Playgroud)

python function parameter-passing python-2.7

4
推荐指数
2
解决办法
1818
查看次数

标签 统计

function ×1

parameter-passing ×1

python ×1

python-2.7 ×1