我正在为终端制作一个简单的游戏(因为我不想在我的 arch 机器上安装图形用户界面)。我想检测按键并相应地更改一个变量,以便当主进程再次循环时它可以看到更改后的变量。我在谷歌上搜索了一个小时试图解决这个问题,但所有的一切要么停止程序等待按键,要么它需要一个 xserver 显示 (pynput)。我如何在后台检测按键?我真的不想为此安装像 pygame 这样的大型 ol 库...
最佳答案
您要找的是 event loop
.这个循环不断地运行你的程序,同时允许回调直接在你的程序内部流动。在 Python3 中,标准库中有一个专门针对此的新模块,称为 asyncio
。 .
The event loop is the central execution device provided by asyncio. It provides multiple facilities, including:
Registering, executing and cancelling delayed calls (timeouts). Creating client and server transports for various kinds of communication. Launching subprocesses and the associated transports for communication with an external program. Delegating costly function calls to a pool of threads. https://docs.python.org/3/library/asyncio-eventloop.html
同步编写 Python 程序(阅读:使用线程)是可能的,但通常不是您所需要的,而且会增加您不应该关心的复杂性。在大多数情况下,通过回调的异步流不太复杂,并且可以防止您遇到死锁、竞争条件或其他与线程相关的问题。
关于python - 在单独线程的终端中监听 Python 按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50984100/