如何异步打印消息并对其进行修改?

2024-05-15 07:59:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在尝试使用asyncio库,并且

我的目标是:制作一个定期显示消息的程序。用户可以随时修改该消息。

我觉得用下面的代码我已经接近解决方案了,但是有一个问题我似乎无法解决

import asyncio
import msvcrt

class PeriodicMessage():
    def __init__(self, message="This is a periodic message. Press M to modify it."):
        self.message = message

    async def write_message(self, sleep_delay=1):
        while True:
            print(self.message)
            await asyncio.sleep(sleep_delay)

    async def change_message(self, sleep_delay=0.01):
        while True:
            if msvcrt.kbhit():
                key_pressed = msvcrt.getch() or None
                if key_pressed == b'm':
                    self.message = input("Enter a new message to display : ")
            await asyncio.sleep(sleep_delay)

    async def main(self):
        await asyncio.gather(self.write_message(), self.change_message())

if __name__ == "__main__":
    periodic_msg = PeriodicMessage()
    asyncio.run(periodic_msg.main())

如果运行此命令,您将看到消息确实会定期显示。您可以按M来修改消息。然而,问题似乎是“input()”函数阻塞了程序,使其不再真正异步。我在某个地方读到过,python中的异步输入并不是一件真正的事情,但我无法确认这一点,因为我只从一个源代码中看到了这一点

也许我完全错了,而我现在正在探索的解决方案就是不对的

有什么想法吗? 提前谢谢


Tags: self程序asyncio消息messageasyncifmain
1条回答
网友
1楼 · 发布于 2024-05-15 07:59:03

完成任务的最佳方法是从PyPI存储库安装包aioconsole,并使用:

self.message = await ainput("Enter a new message to display: ")

当然,在您的演示中,您不断输出的消息(“这是一条周期性消息…”)在一定程度上干扰了演示,因此我稍微更改了消息,并延长了输出消息之间的时间间隔:

import asyncio
from aioconsole import ainput

class PeriodicMessage():
    def __init__(self, message="This is a periodic message. Enter new text to modify it."):
        self.message = message

    async def write_message(self, sleep_delay=5):
        while True:
            print(self.message)
            await asyncio.sleep(sleep_delay)

    async def change_message(self):
        while True:
            self.message = await ainput("Enter a new message to display: ")

    async def main(self):
        await asyncio.gather(self.write_message(), self.change_message())

if __name__ == "__main__":
    periodic_msg = PeriodicMessage()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(periodic_msg.main())

相关问题 更多 >