亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

調度帶有事件循環參數的函數調用

調度帶有事件循環參數的函數調用

瀟湘沐 2023-06-27 13:50:49
您將如何調用帶有參數的函數(在我的代碼中稱為 func)作為 event_loop 的一部分?考慮到這些函數應該在服務器傳入請求時多次調用。async def my_func_1(json_message: dict, writer: StreamWriter) -> bool:    return Trueasync def my_func_2(json_message: dict, writer: StreamWriter) -> bool:    return Trueasync def my_func_3(json_message: dict, writer: StreamWriter) -> bool:    return Trueswitcher = {    "Forward": my_func_1,    "Backward": my_func_2,    "Up": my_func_3}async def dispatcher(reader: StreamReader, writer: StreamWriter):    try:        msg = await reader.readline()        message = ujson.decode(msg.decode())    except Exception:        print("unable to parse json from read stream:" + str(msg.decode()))        if "method" in message:        func = switcher.get(message['method'], UnknownMethod)        # how would you invoke func with arguments as part of the event_loop?        # considering these functions should be invoked multiple times.def init():    loop = asyncio.get_event_loop()    coro = asyncio.start_server(dispatcher, '127.0.0.1', 666, loop=loop)    server = loop.run_until_complete(coro)        try:        loop.run_forever()    except KeyboardInterrupt:        pass    # Close the server    server.close()    loop.run_until_complete(server.wait_closed())    loop.close()if __name__ == '__main__':    init()感謝所有的幫助
查看完整描述

1 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

根據我對您問題的理解,答案是簡單地使用所需參數調用該函數,就像在任何其他上下文中一樣。


# ...

if "method" in message:

    func = switcher.get(message['method'], UnknownMethod)

    await func(message, writer)

# ...


查看完整回答
反對 回復 2023-06-27
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號