如何为我的聊天室模型编写异步输入函数?

时间:2019-06-22 21:02:26

标签: python-asyncio python-3.7 curses

我是asyncio,aioconsole和curses的新手。我正在为应该与aairtc一起运行的聊天室编写模型。我想模拟聊天室中所有客户端之间的p2p连接。我使用curses构建了一个cli,现在尝试编写一个用于用户输入的异步输入函数。如何在我的诅咒窗口中整合aioconsole的ainput?

我已经将cli的evchat类包括在内。 (https://github.com/EvanKuhn/evchat/tree/master/evchat) 我还实现了生产者/消费者过程,该过程产生随机输出并将其打印到控制台。通常,它模拟几个人之间的活跃聊天。没有用户输入,程序将按预期运行。无需用户输入即可生成随机聊天记录。


import os
import json
import datetime
import asyncio
from aioconsole import ainput
import sys
import random
import curses
import ui

from loremipsum import get_sentence

class Prompt:
    """
    #==============================================================
    # The Prompt class prompts the user for text.
    #==============================================================
    """
    def __init__(self, layout, screen):
        self.layout = layout
        self.screen = screen
        self.window = curses.newwin(layout.prompt_rows, 
                      layout.prompt_cols,
                      layout.prompt_start_row, layout.prompt_start_col)
        self.window.keypad(1)
        self.window.addstr('> ')

    def getstr(self):
        "Get an input string from the user"
        return self.window.getstr()

    # ... more functions, more classes


class Message:
    """
    #================================================================
    # Message class
    #================================================================
    """
    def __init__(self, time=None, name=None, text=None):
        self.time = time
        self.name = name
        self.text = tex


class ChatApp:
    """
    #========================================================== 
    # The ChatApp class is contains all lower-level UI classes, plus 
    the main
    # runtime loop.
    #==================================================================
    """
    running = False

    def __init__(self, config, arguments):
        self.config = config
        self.layout = ui.Layout()
        self.args = arguments
        self.screen = None

    # ...more functions

    async def generate_output(self, queue: asyncio.Queue):
        """
        generates random output for mockup purposes, 
        the producer
        """
        name_list = ["Sepp", "Schorsch", "Hansi", "Hildegard", "Vreni"]
        time_delay = random.uniform(0.1, 2)
        rand_name = random.randint(0, 4)
        now = datetime.datetime.now()
        randtext = Message(now, name_list[rand_name], 
                           str(get_sentence(True)))
        # self.history.append(randtext)
        await asyncio.sleep(time_delay)
        await queue.put(randtext)

    async def user_input(self, queue: asyncio.Queue):
        """
        getting user_input
        the producer
        """
        # Get input
        # text = self.prompt.getstr()
        text = asyncio.wait_for(self.prompt.getstr(), timeout=1)
        # Construct and store a Message object
        now = datetime.datetime.now()
        msg = Message(now, self.config.name, text)
        await asyncio.wait_for(queue.put(msg), timeout=0.1)

    async def write_to_console(self, queue: asyncio.Queue):
        """
        coroutine for writing to console, 
        the consumer
        """
        while True:
            msg = await queue.get()
            self.history.append(msg)
            queue.task_done()


if __name__ == "__main__":
    app = ChatApp(conf, args)
    loop = asyncio.get_event_loop()
    try:
        task = loop.create_task(app.start())
        loop.run_until_complete(task)
    except KeyboardInterrupt:
        app.stop()

我希望Sepp&Co.以随机间隔编写随机ipsum句子,而无需用户输入阻止聊天参与者编写内容。就像在whatsapp或其他聊天组中一样。 目前,我只得到这个:我在聊天中写点东西。只有一个人答复,每个人都在等待用户的另一输入。

在Prompt类中没有帮助的是


async def getstr(self):
    "Get an input string from the user"
    text = await self.window.getstr()
    return text

或:


async def getstr(self):
    "Get an input string from the user"
    text = await ainput()
    self.window.addstr(text)

说实话,我不知道如何将输入输入到我的诅咒窗口中。 预先感谢!

1 个答案:

答案 0 :(得分:0)

您可以使用getstr并使用简短的getch(或设置timeout)来代替nodelay