Maybe this SO answer can help? Found on Google using 'python keypress when window is not in front' Answer from JohnnyJordaan on reddit.com
🌐
Reddit
reddit.com › r/learnpython › how to get input even if program isn't focus ?
r/learnpython on Reddit: How to get input even if program isn't focus ?
April 1, 2019 -

Hello,

I try to build a system which takes rectangular screen shoots from part of the screen. The part in question is defined by the user with his mouse and a special key. Each time the special key is pressed, the program should log the mouse position and define the size of the image to save.

My problem is that if i lose focus on the cmd windows of my program (by opening a photo on my desktop for exemple), the program doesn't listen anymore to my keypress. I don't understand how to do so that it keeps listening.

Any suggestion is appreciated as I don't know where to search !

🌐
Reddit
reddit.com › r/learnpython › how to get keyboard events even without focus, on linux?
r/learnpython on Reddit: How to get keyboard events even without focus, on Linux?
September 7, 2015 -

I'm writing a program that automatically types sentences when you press keyboard shortcuts. I'm using autopy.key.type_string() for sending the keyboard events, but I need a way to be able to recognize when the keyboard shortcut is being pressed, even when my Python script doesn't have focus. After Googling a bit, it seems like these are the two most commonly suggested solutions:

  • Make a Tkinter window and get keyboard events from that. This won't work because the Tkinter window needs focus to get keyboard input, and if it has focus that means that type_string() would be sending the text right back to that same window instead of the window I want.

  • Hook some Win32 APIs. This won't work because I'm on Linux.

So is there a way of doing this on Linux? What would you guys recommend?

People also ask

How can I detect any key press in Python without the program losing focus
ANS: You can use libraries like keyboard, pynput, or platform-specific modules like msvcrt (Windows) or curses (Unix-like) to detect key presses globally. The module’s is_pressed() or read_event() and ’s Listener are common cross-platform choices.
🌐
sqlpey.com
sqlpey.com › python › python-detecting-key-presses-without-gui-focus
Python: Detecting Key Presses Without GUI Focus - sqlpey
Can I detect key presses if my Python script is running in the background
ANS: Yes, libraries like keyboard and pynput are designed to work globally, allowing detection of key presses even if your script’s console window is not in focus or if it’s running as a background process, provided the necessary permissions are granted.
🌐
sqlpey.com
sqlpey.com › python › python-detecting-key-presses-without-gui-focus
Python: Detecting Key Presses Without GUI Focus - sqlpey
How to handle special keys like arrow keys in Python
ANS: Libraries like pynput, keyboardcurses, and pygame provide specific constants or methods to identify special keys (e.g., arrow keys, function keys, Enter, Esc). For example, uses Key.esc and uses event names like 'down' for the down arrow.
🌐
sqlpey.com
sqlpey.com › python › python-detecting-key-presses-without-gui-focus
Python: Detecting Key Presses Without GUI Focus - sqlpey
🌐
Readthedocs
pyglet.readthedocs.io › en › latest › programming_guide › keyboard.html
Keyboard input — pyglet v2.1.13
Keyboard focus is where the user’s keyboard input is sent. Desktop operating systems often follow these conventions: ... However, the items above are not guaranteed to be true. For example, pyglet allows you to request focus from the OS by calling Window.activate. However, the OS may not support the feature. Even if it does support it, the OS may not only refuse, but do so without ...
🌐
PyPI
pypi.org › project › keyboard
keyboard · PyPI
Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more. Global event hook on all keyboards (captures keys regardless of focus).
      » pip install keyboard
    
Published   Mar 23, 2020
Version   0.13.5
🌐
Real Python
realpython.com › python-keyboard-input
How to Read User Input From the Keyboard in Python – Real Python
February 20, 2024 - By fetching input and assigning it to variables, your code can react to adjustable conditions rather than just executing static logic flows. This personalizes programs to individual users. The input() function is the simplest way to get keyboard ...
Find elsewhere
🌐
sqlpey
sqlpey.com › python › python-detecting-key-presses-without-gui-focus
Python: Detecting Key Presses Without GUI Focus - sqlpey
July 25, 2025 - For scenarios involving SSH sessions, sshkeyboard offers a convenient way to capture keyboard input that works reliably even over network connections. ... from sshkeyboard import listen_keyboard def handle_press(key): print(f"'{key}' pressed") def handle_release(key): print(f"'{key}' released") print("Listening for keyboard events. Press ESC to stop.") listen_keyboard( on_press=handle_press, on_release=handle_release, ) This solution provides a unified, cross-platform approach without external dependencies beyond standard Python libraries.
🌐
Python
mail.python.org › pipermail › tutor › 2006-April › 046117.html
[Tutor] Capture keyboard input even without python in focus
April 1, 2006 - " See tutorial here: http://www.cs.unc.edu/~parente/tech/tr08.shtml<http://www.cs.unc.edu/~parente/tech/tr08.shtml> francois On 01/04/06, Ars <aguffabuff at hotmail.com> wrote: > > What commands could capture input from the keyboard (and the mouse while > we're at it) even when the running python program isn't the program in > focus?
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Reading key presses in Python (without pausing execution) - Raspberry Pi Forums
November 17, 2021 - I think suggestions tend to focus on using the "getch" method in the "curses" module. Have a search for those words and see what comes up. Sorry, on my phone so can't quickly find some links for you. RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc. ... Use The Keyboard Library For Python Terminal Replace "X.XX" with your python version or remove it if installed only one version
🌐
Google Groups
groups.google.com › g › autokey-users › c › OOY8Bt6pajA
Sending Keypresses without Activating Window
xdotool lets you programatically (or manually) simulate keyboard input and mouse activity, move and resize windows, etc. http://www.semicomplete.com/projects/xdotool/xdotool.xhtml#keyboard_commands · 2. Then in Autokey, create a hotkey script like the following to send keystrokes to an inactive window. system.exec_command("xdotool search --name wow2 key 1", getOutput=True)
🌐
pytz
pythonhosted.org › pyglet › programming_guide › working_with_the_keyboard.html
Working with the keyboard
You can request keyboard focus for a window with the activate method, but you should not rely on this -- it may simply provide a visual cue to the user indicating that the window requires user input, without actually getting focus. Windows created with the WINDOW_STYLE_BORDERLESS or WINDOW_STYLE_TOOL style cannot receive keyboard focus. It is not possible to use pyglet's keyboard or text events without a window; consider using Python built-in functions such as raw_input instead.
🌐
Reddit
reddit.com › r/learnpython › how do you capture keystrokes only when focused?
r/learnpython on Reddit: How do you capture keystrokes only when focused?
September 22, 2023 -

I'm working on a little TUI file manager written in Python and C to try to bone up on programming again, but I'm not sure how you're actually supposed to go about capturing keystrokes only when the terminal running it is focused. Pynput and Keyboard modules both seem to capture input system wide.

On Linux, specifically Debian btw.

Top answer
1 of 2
10

Ok, i figured it out, figured I would post the answer.

pythons keyboard module, docs and source here

as stated in the "Known Limitations" section, (even though I don't think this is a limitation!)

"To avoid depending on X, the Linux parts reads raw device files (/dev/input/input*) but this requires root."

So this does bring up security issues obviously since the program now needs root privileges, but for my case this is not an issue.

pip install keyboard

simple program

import keyboard
import time

def key_press(key):
    print(key.name)

keyboard.on_press(key_press)

while True:
    time.sleep(1)
2 of 2
0

I am currently working on a similar problem. I got an idea how to solve this. But did not try it yet. Not sure if I should put this into a new question.

  • set up a virtual console that automatically logs in a user
  • this console does not show an interactive shell (bash) but just a process that listens for key-presses and sends them to MPD

That's it. You still may switch to a standard console using Ctrl-Fx and then log-in normally without any side effects like unwanted control of the MPD.

There are still several problems unsolved:

  • does linux open up the virtual consoles at all if there is no monitor attached?

  • how to set up this console? /etc/login.defs?

  • what language and library to use for the listener process (I implemented everything in python until now)

  • how to pass the events to MPD. (through mpc command line client or python mpc client library?)

I marked this as community wiki. So anybody feel free to contribute to this answer.

Background: I implemented a headless audio-player using MPD on raspberry pi that currently is controlled via GPIO pins. Now I would like to be able to control it via keyboard as well.

🌐
Pierian Training
pieriantraining.com › home › how to wait for a keypress in python
How to Wait for a Keypress in Python - Pierian Training
April 28, 2023 - If you’re running Python on a different operating system, you’ll need to use a different approach to wait for a keypress. One way to wait for a keypress in Python is by using the `getch()` function from the `keyboard` module.
🌐
Reddit
reddit.com › r/learnpython › any way to send a keyboardinterrupt to an unfocused python window via keypress?
r/learnpython on Reddit: Any way to send a KeyboardInterrupt to an unfocused Python window via keypress?
May 18, 2018 -

I've been messing around with Pyautogui and having it do keystrokes and mouse clicks and it works great, but it obviously unfocuses the python shell with the mouse clicks. Some parts move quick and it's iffy to click the shell to focus it and then hit Ctrl+C. I'm hoping there is a way to program a keypress or something into the script to kill it whenever I need to.

One thought I had was to set the shell to the first slot on the taskbar in Windows and then attach a function to a keystroke, but I'm not sure how to attach a function to a keystroke. So something like this pseudocode:

If keypress = Ctrl + Shift + S:
    keyboard.press_and_release('Win+1')
    keyboard.press_and_release('Ctrl+C')

Any ideas on how to accomplish this would be great though. Thanks guys.

🌐
Delft Stack
delftstack.com › home › howto › python › python detect keypress
How to Detect Keypress in Python | Delft Stack
February 12, 2024 - The keyboard.Listener is used as a context manager that starts the listening process. The listener.join() method is called to wait until the listener stops, which happens when the escape key is pressed. ... While there are multiple methods to capture key inputs in Python, the readchar library offers a simple and efficient way to detect single keypresses.
🌐
Narkive
tutor.python.narkive.com › spgK42zp › get-keyboard-input-while-other-program-is-in-focus
[Tutor] Get keyboard input while other program is in focus?
Post by Jack What commands can ... is in focus? I think Pygame and TKInter have a capture-all-keys function, but this might also prevent the keypresses from actually going to the target application. Post by Jack thanks, Jack ------------------------------------------------------------------------ _______________________________________________ http://mail.python.org/mailm...