python - 在单独线程的终端中监听 Python 按键

标签 python linux keyboard

我正在为终端制作一个简单的游戏(因为我不想在我的 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/

相关文章:

python - 在 Ubuntu 12.04 上安装 Pandas 失败

linux - Unix 路径需要重新排序

linux - sed 拆分单行文件并处理结果行

keyboard - 单击 Titanium 中 tableView 内的文本字段时隐藏键盘(模糊)

python - 如何使用需要用户定义类型表参数的 SQLAlchemy 调用存储过程

python - 访问列表时的语法错误

react-native - 如何在 React native 的 WebView 中隐藏键盘工具栏(InputAccessoryView)? (iOS)

iphone - 根据键盘和预测 TextView iOS 8 向上或向下移动我的工具栏

python - 如何使用pipreqs创建requirements.txt文件

linux - 比较两个文件并合并数据