1
from pygame import key
keys = key.get_pressed()

I'm running this on Debian 10, Python 3.7.3, pygame 2.0.1.

  • Edit 1: I assume that using only the "key" module does not require pygame.init() because there is not pygame.key.init() method, but some other modules like "mixer" does. Having pygame.init() in the script still results in the same error, with an additional error before that: "error: XDG_RUNTIME_DIR not set in the environment."

@furas also pointed out that I need to define a window for pygame to work, but I'm building a headless system with no GUI so I want to avoid unnecessary memory consumption. Is there a workaround that allows me to use the pygame key module to detect keyboard input without having to create a window?

Phuc Mai
  • 41
  • 3
  • Could you please share what makes you think that using only the key module doesn't require the initialisation? – Pac0 Jun 07 '21 at 21:30
  • 1
    system (Windows, Linux, MacOS) sends keys/mouse events only to active window - so you have to create window in PyGame to get key/mouse events. If you want to get keys without window then you should use module like `keyboard` or `pynput`. – furas Jun 07 '21 at 22:04
  • 1
    @Pac0 for submodules like "mixer" they provide `init()` method, while the "key" module does not, so I think `pygame.init()` will only call the `init()` methods available in the submodules. – Phuc Mai Jun 08 '21 at 09:30
  • @furas thanks, I want to try out this module because the APIs seem easy to implement. I will try `pynput` next, as `keyboard` seems to require root privilege. – Phuc Mai Jun 08 '21 at 09:33
  • @PhucMai Thanks, your rationale makes sense. But you don't get the error anymore, if you call `pygame.init()`, right? – Pac0 Jun 08 '21 at 10:04
  • `pygame.init()` removes error but it will still not gives keys - you would have to create window and make it active (focused) and then system will send keys/mouse event to this window and you can get it in code. But you would have to also run loop with `pygame.event.get()` to update data in table which you get with `get_pressed()` – furas Jun 08 '21 at 13:06
  • @Pac0 with `pygame.init()` I actually still have the same error, additionally also this error "error: XDG_RUNTIME_DIR not set in the environment.", but that makes sense because I'm building a headless system and it is missing a lot of libraries. I do wish to save memory and processing capability, so I will not create a window with pygame. – Phuc Mai Jun 09 '21 at 18:13
  • these are relevant details for your problem, making it different from the duplicate target. Could you please [edit](https://stackoverflow.com/posts/67878805/edit) your question and include them? I'll gladly vote for reopening it. – Pac0 Jun 10 '21 at 06:02
  • 1
    @Pac0 thanks, I just added those info in the main question. – Phuc Mai Jun 11 '21 at 07:59

0 Answers0