您將如何調用帶有參數的函數(在我的代碼中稱為 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)
# ...
添加回答
舉報
0/150
提交
取消