我想和aiortc建个聊天室。首先,我想构建一个以urwid作为cli和异步的模型。urwid部分已经运行良好,用户输入是可能的。我知道,我想运行一个协同机制,生成随机文本,并作为聊天客户端在那个聊天室发短信。
我尝试过使用main循环作为异步协同器运行我的urwid函数,但没有成功。我不知道如何将异步函数集成到我的urwid主循环中。
def unhandled(key):
"""
functin to handle input
"""
global TEXT_INPUT
global lw_user_input
global lw_chatroom
global listbox_chatroom
if not isinstance(key, tuple):
if key == 'enter':
del lw_user_input[-1]
# create widegt and fill with user input
lw_chatroom.append(widget)
TEXT_INPUT = ""
listbox_chatroom.set_focus(len(lw_chatroom)-1, 'above')
elif key == 'esc':
raise urwid.ExitMainLoop()
elif key == 'backspace':
if len(lw_user_input) > 0:
user_input = lw_user_input[0].get_text()[0]
user_input = user_input[:-1]
del lw_user_input[-1]
TEXT_INPUT = user_input
lw_user_input.append(urwid.Text(TEXT_INPUT))
else:
TEXT_INPUT += key # repr(key)
if len(lw_user_input) > 0:
del lw_user_input[-1]
lw_user_input.append(urwid.Text(TEXT_INPUT))
else:
lw_user_input.append(urwid.Text(key))
def generate_output():
global lw_chatroom
global listbox_chatroom
while True:
# generate text and widgets and post with delay
lw_chatroom.append(chat_widget)
listbox_chatroom.set_focus(len(lw_chatroom)-1, 'above')
def create_cli():
# generate all widgets
uloop = urwid.MainLoop(frame, palette, screen,
unhandled_input=unhandled)
uloop.start()
if __name__ == '__main__':
create_cli()我希望异步运行generate_output()和未处理(键)。我不知道该怎么做。
发布于 2019-07-14 10:27:13
好吧,我想出来了。
它很简单:
asyncio.get_event_loop() ev_loop = urwid.AsyncioEventLoop(loop=aloop)循环=urwid.MainLoop(帧、调色板、屏幕、unhandled_input=unhandled、event_loop=ev_loop) aloop.create_task(generate_output()) loop.run()
https://stackoverflow.com/questions/56966547
复制相似问题