簡體   English   中英

如何使用urwid和asyncio創建異步程序?

[英]How can I create an asynchronous program with urwid and asyncio?

我想與aiortc建立一個聊天室。 首先,我想用urwid作為cli和asyncio構建一個樣機。 urwid部分已經運行良好,可以輸入用戶信息。 我知道要運行一個協程,該協程可以生成隨機文本,並在該聊天室中作為聊天客戶端發短信。

我試圖用mainloop作為異步協程運行urwid函數,但沒有成功。 我不知道如何將異步函數集成到我的urwid mainloop中。

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()和unhandled(key)。 我不知道該怎么辦

好的,我知道了。

就這么簡單:

 aloop = asyncio.get_event_loop() ev_loop = urwid.AsyncioEventLoop(loop=aloop) loop = urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled, event_loop=ev_loop) aloop.create_task(generate_output()) loop.run() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM