The standard approach is to use the select module.
However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.
Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.
Answer from S.Lott on Stack OverflowI want to write a simple program in the terminal that takes in non-blocking I/O input basically. The idea as as follows (it's very simple):
while True:
print("#"*length_bar)
if keypress: # runs in "background" or concurrent with main loop
length_bar += 1Now, the problem is that I have trouble finding a way to get non-blocking keyboard input from the user while print stuff in the terminal as well. I want this bar to continuously print while waiting actively for board input. Been banging my head against this devilishly simple problem for an hour or so now but can't seem to find a satisfactory answer on google or stackoverflow ...
The standard approach is to use the select module.
However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.
Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.
A solution using the curses module. Printing a numeric value corresponding to each key pressed:
import curses
def main(stdscr):
# do not wait for input when calling getch
stdscr.nodelay(1)
while True:
# get keyboard input, returns -1 if none available
c = stdscr.getch()
if c != -1:
# print numeric value
stdscr.addstr(str(c) + ' ')
stdscr.refresh()
# return curser to start position
stdscr.move(0, 0)
if __name__ == '__main__':
curses.wrapper(main)
I'm trying to create a platformer in Python 3.4.3 on OS X. Unfortunately, using event.key doesn't return anything but 0 for the letter keys. It works for the arrow keys:
IF event.key == pygame.K_DOWN: returns a value if the down key is pressed.
But not for WASD:
IF event.key == pygame.K_s: does not return a value if the s key is pressed, no matter what modifiers are active.
And using the curses library gives me a terminal error when I initialize it.
Is there any way to detect keycodes without importing a library?
I can't find anything but I figured someone might know something.
I need to detect keyboard presses in a python3 script running on a headless linux server (Unbuntu).
I can't use pynput because that relies on X, which doesn't exist.
I can't use keyboard, because for some inexplicable reason, it crashes rtmidi, the library I use for reading midi input. Why? No idea. I just add one line of code like "keyboard.wait" and rtmidi crashes with this error:
TypeError: 'tuple' object is not callable Exception ignored in: 'rtmidi._rtmidi._cb_func'
So now I'm stuck. Any ideas?
I have a program which takes user input and outputs an answer. Now, I'd like to make it so that when the user presses a certain key, it exits the program. But how can you make it so that the program tries to detect that exit keypress at all times? Even when its looking for a user input?
I am only able to do one step at a time, like user input/output, then exit, or I can put exit first but that will just exit before anything happens
Thanks in advance!
I need to detect if any key is pressed but i cannot wait until the user press anything
Like he only gonna press any key if he wants to stop the program,so the program need to continue while he dont press nothing
Ps:sorry my bad english
from datetime import datetime
import os
from msvcrt import getch
from time import sleep
def get_down(time):
print('press ENTER to cancel \n')
while True:
key = ord(getch()) #the program stop wanting the user to press a key
if key == 13:
print('You cancel the operation')
break
if time == hours:
print("The system is gonna turn off")
sleep(5)
os.system("shutdown /s /t 1")
hours = datetime.now().strftime('%H:%M')
print('Now is: {}'.format(hours))
get_down(str(input('When you want to shutdown? (hh:mm):')))I’m on Mac and want to display “press any key to continue” during my code.
The only ways I’ve found to check for a single key press (without having to press enter) require the logging in as admin.
I understand why this might be - but is there any way to achieve this elegantly?
I'm trying to create a platformer in Python 3.4.3 on OS X. Unfortunately, using event.key with Pygame doesn't return anything but 0 for the letter keys. It works for the arrow keys:
IF event.key == pygame.K_DOWN: returns a value if the down key is pressed.
But not for WASD:
IF event.key == pygame.K_s: does not return a value if the s key is pressed, no matter what modifiers are active.
And using the curses library gives me a terminal error when I initialize it.
Is there any way to detect keycodes without importing a library?
So i am trying to make an AFK mouse mover for testing purposes and i saw online people used "keyboard". However, almost every tutorial i saw needed a specific key, and i want ANY key, be it space, windows key, a, b, enter, whatever...Here is my code (sorry if it's garbage, i'm still learning a lot). It gives out an error:
TypeError: is_pressed() missing 1 required positional argument: 'hotkey'
What do i need to do?
import pyautogui as pag
import time as time
import random as random
import keyboard as keyboard
cur_cords = pag.position()
afk_counter = 0
def move_mouse():
while True:
global cur_cords
global afk_counter
if pag.position() == cur_cords and keyboard.is_pressed() == False:
afk_counter += 1
else:
afk_counter = 0
cur_cords = pag.position()
if afk_counter > 5:
x = random.randint(1, 2560)
y = random.randint(1, 1440)
pag.moveTo(x, y, 0.5)
cur_cords = pag.position()
print(f"AFK counter timer: {afk_counter}")
time.sleep(2)
move_mouse()I have a python script which needs to run an infinite loop until the user presses "q", but it also needs to be able to do stuff within the loop. I found some excellent looking code at https://www.reddit.com/r/learnpython/comments/zwz0k9/comment/j1yakmx/ however it appears the keyboard Python module requires you to be root in order to use it, which is not suitable for my use case.
For ease of viewing here's a slightly modified version of the code from the other post:
import time
import keyboard
import threading
import queue
def look_for_key(keys: list[str], q: queue.Queue, done: threading.Event):
while not done.is_set():
for key in keys:
if keyboard.is_pressed(key):
q.put_nowait(key)
done = threading.Event()
q = queue.Queue()
look_thread = threading.Thread(target=look_for_key, args=(['q'], q, done))
look_thread.start()
big_loop = True
while big_loop:
# Do stuff here
while not q.empty():
key = q.get_nowait()
if key == "q": # check if the Q key is pressed
big_loop = False
done.set()
break # exit the loop
look_thread.join()Can anyone suggest a way of achieving this that doesn't require root permissions on Linux?
EDIT: I tried using pynput as this looked promising, but it requires an X server apparently.