Evil Python Lesson 6: Keyboard Input!
The function input returns a variable of type str . If x = input() is executed and 5 Enter is typed, then type(x) will yield <class ‘str’> .
Notice that the variable age stores a number but its type is str .
Keyboard Listening Using the pynput Package
Recall that we can create a keyboard listener using the pynput package’s keyboard module. We define two callback functions to which we set the on_press and on_release parameters of the keyboard.Listener function, which returns a keyboard listener. The callback functions press_callback and release_callback will then execute every time a key is pressed or released, respectively.
The reason we need to use l.start() and l.join() is a bit complicated, so just remember that pynput keyboard listeners need to do both!
Continuous Input: pynput
Recall from the previous lesson’s assignments that games can be created using Python’s built-in input function, while more advanced (and more fun) games can be created in which the user does not have to press Enter after every key press.
Installing pynput
The pynput package allows Python to “listen” to keyboard input continuously.
To install pynput , complete the following:
- Navigate to folder containing the .py file using cd foldername1/foldername2 , etc.
- Read the PACKAGE INSTALL NOTE below, then type pip install pynput
- Run a game called (for example) filename.py using python filename.py .
- If you get an error that contains the words user or permissions , run the program using sudo python filename.py . You may be prompted for a password.
- Type python -m venv venv
- Type source venv/bin/activate
- Type pip install pynput
Overview: “Listening” to Input
So far, we have written Python code that prompts the user for textual input through the command prompt with the built-in Python input function. While typing our responses into the command prompt, we can navigate away from the window or type and erase, and Python won’t know the difference until we press Enter .
By contrast, pynput is a keyboard listener, which means it interacts with your operating system (Windows, Mac OS, or Linux) so that it knows about all keyboard actions. In fact, pynput can even control the keyboard and trigger automated key-presses.
You can view the official pynput keyboard documentation here.
Events and Callbacks
The way pynput handles keyboard input is by being aware of all keyboard actions, called “events”, and to respond to them by executing functions, called “callbacks”.
The events that pynput can respond to are key-presses and key-releases.
A very simple key-press callback function that prints the pressed key looks like this:
Callbacks take a parameter — here it is called key . When we register this function as a callback, pynput sends the identity of the pressed key as an argument to this function when it executes.
To register this function as a callback, we create an object of the the pynput.keyboard.Listener class and its start and join method. For now, just copy this syntax to implement a keyboard listener:
The keyboard.Listener method takes a keyword parameter called on_press , which is here set to our callback press_callback . This function is executed whenever any key is pressed, with an argument that gives the identity of the pressed key, which becomes the parameter of the callback, key .
Keyboard Listening: pynput.keyboard.Listener
“Press” and “Release”: on_press and on_release
We can implement a more complicated listener that responds to key-presses as well as key-releases.
The key Variable is not a Python String: key.char
We used the following key-press callback:
When we use str.format to print the pressed key, the key variable automatically returns a Python string to be printed (using a __str__ method). But if we had tried:
we would see TypeError: unsupported operand type(s) for +: ‘KeyCode’ and ‘str’ .
So, the key variable holds more than just a string identifying the key. However, that’s usually what we want. To access the str identifier for the pressed key, you can use the key.char attribute:
Note that in the first version of the code, we would see output like:
That’s because key.__str__ returns a nicely-formatted string identifying the key pressed, whereas key.char contains just the character associated with that key.
Unfortunately, key.char can only be called for keys that are associated with a character (like A , 5 , and = ). If key is referring to the Enter key, for example, then key simply does not have the attribute char .
Python has a built-in function called hasattr (“has attribute”) that checks whether a variable has a certain attribute, and it comes in handy here:
Responding To Individual Keys
Using key.char , we can respond to individual keypresses:
Some special keys, like esc , have special pynput variables associated with them:
Stop Listening to Me!
We can always stop a keyboard listener by returning False from a callback function:
Keyboard Control: pynput.keyboard.Controller
We can instruct pynput to press a key with the following:
Make sure to always release keys that you press using code!
The possibilities are great by just pressing character keys, but we can also press special keys:
Pressing a key once is no big deal, but code lets us iterate!
Even better? There is a type function that will type a whole string:
Controling and Listening
This code autocompletes a word!
Assignments
Describe what the following code does:
Make an autocomplete tool. Write some code so that when you type the first letter of your name, the rest of your name is typed out. If your name contains two copies of the letter it starts with, you will have difficulty, so pick another word!
- Try Making code that autocompletes only after you’ve typed the first TWO letters of your name!
Return to the previous lesson’s assignment 3 and mod some of the advanced games with continuous input!
How to detect key presses?
I am making a stopwatch type program in Python and I would like to know how to detect if a key is pressed (such as p for pause and s for stop), and I would not like it to be something like raw_input , which waits for the user’s input before continuing execution.
Anyone know how to do this in a while loop?
I would like to make this cross-platform but, if that is not possible, then my main development target is Linux.
17 Answers 17
Python has a keyboard module with many features. Install it, perhaps with this command:
Then use it in code like:
For those who are on windows and were struggling to find an working answer here’s mine: pynput
The function above will print whichever key you are pressing plus start an action as you release the ‘esc’ key. The keyboard documentation is here for a more variated usage.
Markus von Broady highlighted a potential issue that is: This answer doesn’t require you being in the current window to this script be activated, a solution to windows would be:
More things can be done with keyboard module. You can install this module using pip install keyboard Here are some of the methods:
Method #1:
This is gonna break the loop as the key p is pressed.
Method #2:
It will wait for you to press p and continue the code as it is pressed.
Method #3:
It needs a callback function. I used _ because the keyboard function returns the keyboard event to that function.
Once executed, it will run the function when the key is pressed. You can stop all hooks by running this line:
Method #4:
This method is sort of already answered by user8167727 but I disagree with the code they made. It will be using the function is_pressed but in an other way:
It will break the loop as p is pressed.
Method #5:
You can use keyboard.record as well. It records all keys pressed and released until you press the escape key or the one you’ve defined in until arg and returns a list of keyboard.KeyboardEvent elements.
Notes:
- keyboard will read keypresses from the whole OS.
- keyboard requires root on linux
As OP mention about raw_input — that means he want cli solution. Linux: curses is what you want (windows PDCurses). Curses, is an graphical API for cli software, you can achieve more than just detect key events.
This code will detect keys until new line is pressed.
For Windows you could use msvcrt like this:


Use this code for find the which key pressed

neoDev’s comment at the question itself might be easy to miss, but it links to a solution not mentioned in any answer here.
There is no need to import keyboard with this solution.
Solution copied from this other question, all credits to @neoDev.
This worked for me on macOS Sierra and Python 2.7.10 and 3.6.3

Use PyGame to have a window and then you can get the key events.
For the letter p :

Non-root version that works even through ssh: sshkeyboard. Install with pip install sshkeyboard ,
then write script such as:
And it will print:
When A key is pressed. ESC key ends the listening by default.
It requires less coding than for example curses, tkinter and getch. And it does not require root access like keyboard module.
You don’t mention if this is a GUI program or not, but most GUI packages include a way to capture and handle keyboard input. For example, with tkinter (in Py3), you can bind to a certain event and then handle it in a function. For example:
With the above, when you type into the Text widget, the key_handler routine gets called for each (or almost each) key you press.

I made this kind of game based on this post (using msvcr library and Python 3.7).
The following is the main function of the game, that is detecting the keys pressed:
If you want the full source code of the program you can see it or download it from GitHub
The secret keypress is:

Using the keyboard package, especially on linux is not an apt solution because that package requires root privileges to run. We can easily implement this with the getkey package. This is analogous to the C language function getchar.
We can add this in a function to return the pressed key.

This is from the openCV package. The delay arg is the number of milliseconds it will wait for a keypress. In this case, 1ms. Per the docs, pollKey() can be used without waiting.
The curses module does that job.
You can test it running this example from the terminal:

Here is a cross-platform solution, both blocking and non-blocking, not requiring any external libraries:
You can use key_pressed() inside a while loop:
You can also check for a specific key:
Find out special keys using print_key() :
Or wait until a certain key is pressed:

I was finding how to detect different key presses subsequently until e.g. Ctrl + C break the program from listening and responding to different key presses accordingly.
Using following code,
It will cause the program to keep spamming the response text, if I pressed arrow down or arrow up. I believed because it’s in a while-loop, and eventhough you only press once, but it will get triggered multiple times (as written in doc, I am awared of this after I read.)
At that moment, I still haven’t went to read the doc, I try adding in time.sleep()
This solves the spamming issue.
But this is not a very good way as of subsequent very fast taps on the arrow key, will only trigger once instead of as many times as I pressed, because the program will sleep for 0.5 second right, meant the "keyboard event" happened at that 0.5 second will not be counted.
So, I proceed to read the doc and get the idea to do this at this part.
Now, it’s working fine and great! TBH, I am not deep dive into the doc, used to, but I have really forgetten the content, if you know or find any better way to do the similar function, please enlighten me!
Руководство по модулю клавиатуры Python
Python является одним из наиболее подходящих языков для автоматизации задач. Будь то повторяемый (этический) веб-скоб через некоторое время, запуск некоторых программ при запуске компьютера или автоматизацию отправки повседневных электронных писем, Python имеет много модулей, которые облегчают вашу жизнь.
Одним из них является модуль под названием keyboard, который полностью контролирует вашу клавиатуру. С помощью данного модуля вы можете печатать что угодно, создавать горячие клавиши, сокращения, блокировать клавиатуру, ждать ввода и т. д.
В этом руководстве мы рассмотрим, как настроить и использовать модуль клавиатуры в Python.
Примечание: Приложения, работающие с автоматизацией человекоподобных процессов, должны разрабатываться этично и ответственно. Модуль клавиатуры сделан так, чтобы быть очень заметным, и, таким образом, делает его одновременно обескураживающим и прозрачным, если кто-то использует его для создания клавиатурных шпионов или вредоносных ботов.
Установка модуля клавиатуры
Версия Python, используемая в этом руководстве, равна 3.8. Однако модуль клавиатуры может работать как с Python 2.x, так и с Python 3.x.
Если вы используете Linnux, чтобы использовать эту библиотеку, вы должны установить ее от root. Если вы этого не сделаете, вы получите:
Кроме того, при запуске сценария вы должны запускать его с правами суперпользователя:
В Windows и macOS, поскольку привилегии работают совсем по-другому — вы можете установить его просто через pip и запустить сценарии:
Примечание: Для MacOS вам, возможно, придется разрешить терминалу или другим приложениям изменять состояние вашей машины, например, путем ввода текста. Также имейте в виду, что по состоянию на сентябрь 2021 года библиотека все еще находится в экспериментальном состоянии на MacOS.
Функция модуля клавиатуры
В этом модуле есть много функций, которые можно использовать для имитации действий клавиатуры.
keyboard.write(message, [delay])- пишет сообщение с задержкой или без нее.
keyboard.wait(key) — блокирует программу до тех пор, пока не будет нажата клавиша. Ключ передается в виде строки («пробел», «esc» и т.д.)
keyboard.press(key)- нажимает клавишу и удерживается до вызова функции release(key)
keyboard.release(key)- выпускает ключ.
keyboard.send(key)- нажимает и отпускает клавишу.
keyboard.add_hotkey(hotkey, function)- создает hotkey, которая при нажатии выполняет function.
keyboard.record(key)- записывает активность клавиатуры до нажатия key.
keyboard.play(recorded_events, [speed_factor]) — воспроизводит события, записанные with keyboard.record(key) функция, с дополнительным speed_factor.
Тем не менее, мы рассмотрим все это. Вот быстрый пример:
Приветственное сообщение появляется на экране в терминале, как будто вы его написали. Вы можете очень легко автоматизировать команду и создать для нее псевдоним горячей клавиши. Вот (грубый) пример выхода из REPL Python, написания команды curl:
Функции write() и wait() клавиатуры
Команда write() записывает сообщение, как мы видели ранее, с необязательной задержкой при запуске. Если задержка не установлена, запись выполняется мгновенно. Это очень хорошо сочетается с функцией wait (), которая ожидает нажатия определенной клавиши.
Например, мы можем создать импровизированный макрос, привязанный, скажем, к 1, который отвечает на этот ввод новым сообщением. Обратите внимание, что вместо этого есть фактический способ создания горячих клавиш, который мы рассмотрим позже.
Мы создадим бесконечный цикл True, чтобы проверить, нажата ли клавиша, и вы можете запустить сценарий в фоновом режиме:
Примечание: Специальные символы не поддерживаются этой функцией, поэтому, если вы добавите, скажем, ! — вы получите исключение остановки.
Функции клавиши press() и release()
Поскольку сложно имитировать press () и release(), чтобы действия были видны, мы также увидим в действии record() и play() .
Функция press() нажимает клавишу и отпускает ее, когда вы вызываете release() на той же клавише.
Тем не менее, вы можете удерживать некоторые специальные клавиши, такие как [SHIFT] или [CTRL] следующим образом:
Функции клавиатуры record() и play()
Речь не всегда идет о вводе новых клавиш — иногда вы хотите записать происходящий и воспроизвести это. Имейте в виду, что вам понадобятся права администратора для записи любого подобного ввода, так как технология может быть легко использована для создания кейлоггеров.
Функция record() принимает ключ запуска, до которого она записывает, и возвращает последовательность событий типа KeyboardEvent. Затем вы можете поместить эту последовательность событий в функцию play(), которая точно воспроизводит их, с дополнительным аргументом speed_factor. Он действует как множитель скорости исходных событий:
Если мы напечатаем recorded_events, они будут выглядеть примерно так:
Функция клавиатуры send()
Функция send() включает в себя press () и release () вместе и используется для отдельных клавиш, в отличие от функции write(), которая используется для целых предложений:
После нажатия клавиши s воспроизводятся клавиши w и a.
Функция press() также может принимать комбинации нажатых клавиш. Вы можете отправить комбинацию «ctrl + shift + s», например, и должен появиться диалог для сохранения файла, если вы находитесь в приложении, которое поддерживает эту операцию:
Хотя это неправильный способ добавить горячие клавиши. Также вы можете использовать функцию add_hotkey().
Функция клавиатуры add_abreviation()
Функция add_abbreviation() является довольно изящной, так как она позволяет определять сокращения для длинных входных данных и заменяет сокращенные версии сохраненными полными версиями.
Например, подобно тому, как такие службы, как Google, сохраняют вашу электронную почту для большинства форм ввода, вы можете создать свою собственную аббревиатуру и запустить ее через [SPACE]:
Во время выполнения, если вы введете @, за которым следует [ПРОБЕЛ] — ввод в длинной форме заменит введенный @.
Функция клавиатуры add_hotkey()
Функция add_hotkey() принимает горячую клавишу, которую вы хотите сохранить, или комбинацию клавиш и функцию. Здесь легко передать анонимные лямбда-функции, хотя вы также можете добавить именованные функции.
Например, давайте добавим горячую клавишу для CTRL+j, которая запускает лямбда-функцию, регистрирующей это:
Горячая клавиша ctrl + alt + p сохраняется, и при нажатии этой комбинации вы должны увидеть вывод лямбды.
Заключение
Модуль клавиатуры представляет собой легкую и простую библиотеку, используемую для моделирования нажатий клавиш и простой автоматизации в Python. Он не очень функциональный, но может быть использован для автоматизации некоторых задач, которые вы можете выполнять в своей повседневной работе, или просто для развлечения.
Detect keypress in Python

Python allows us to work with user input in its programs. We can also work with hardware devices in Python.
In this article, we will discuss how to detect keypress in Python.
Table of Contents
Using the keyboard module to detect keypress in Python
The keyboard module is well equipped with different functions to perform operations related to keyboard input, detecting-simulating key presses, and more. This module works normally on Windows but requires the device to be rooted on Linux devices. To detect keypress, we can use a few functions from this module.
The read_key() function from this module is used to read the key pressed by the user. We can check whether the pressed key matches our specified key.