We use some essential cookies to make our website work.

We use optional cookies, as detailed in our cookie policy, to remember your settings and understand how you use our website.

carlo_a
Posts: 1
Joined: Mon Jun 29, 2015 3:47 pm

Reading key presses in Python (without pausing execution)

Mon Jun 29, 2015 3:57 pm

Hi all, I'm both a Pi and Python novice and was wondering about the most efficient way to read the state of the keyboard in Python on the Pi.

I'd like to do something like read the state of a key every 1/10th of a second, and do something, otherwise continue executing as normal.

Code: Select all

while True:
    key = read_state(SPECIFIC KEY) #Return True is key is pressed
    if key:
        do something
    time.sleep(0.1)
The important thing is that I don't want my script to stop and wait for user input to continue execution. I know that pygame has some of these functions, but I'd like to access them without initializing pygame's graphical overhead - I'd like this script to be entirely command-line based.

Any help would be appreciated, and sorry if this isn't clear! Thanks!

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Reading key presses in Python (without pausing execution

Mon Jun 29, 2015 5:41 pm

This is a fairly common question in this forum. 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.

PyDev-Sushant
Posts: 1
Joined: Tue Mar 02, 2021 2:25 pm

Re: Reading key presses in Python (without pausing execution)

Tue Mar 02, 2021 2:31 pm

Use The Keyboard Library For Python

Terminal
Replace "X.XX" with your python version or remove it if installed only one version

Code: Select all

pythonX.XX -m pip install keyboard
]

PYTHON

Code: Select all

import keyboard

while True:
	if keyboard.is_pressed('a'):
		print('a key has ben pressed')
		
	print(1)
	print(1+2)


Return to “Python”