Python event loop does not work properly with stdin

南楼画角 提交于 2019-12-06 14:29:29

You’re using asyncio improperly in the first setup. You shouldn’t need to interpose it with the threading module.

My recommended setup for this is to create an async function main which contains an infinite loop where you ask for input and create tasks. Then, you can run main from an event loop after you’re done declaring it.

Mind you, awaiting the tasks you create inside main in the above setup is optional; since stdout is guaranteed to be synchronized by the kernel (I’m 70%ish sure this is true,) you can have as many tasks as you want running printer() at a time. However, if you do await the tasks, your program won’t print out while the user is trying to input; it’ll call printer(), which writes to stdout, first, and only ask for the next set of input after printer() has completed.

Hope that answers your question. See the below documentation as an additional resource.

https://docs.python.org/3/library/asyncio-task.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!