How to Wait for a Pressed Key

How do I wait for a pressed key?

In Python 3, use input():

input("Press Enter to continue...")

In Python 2, use raw_input():

raw_input("Press Enter to continue...")

This only waits for the user to press enter though.


On Windows/DOS, one might want to use msvcrt. The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT):

import msvcrt as m
def wait():
m.getch()

This should wait for a key press.


Notes:

In Python 3, raw_input() does not exist.

In Python 2, input(prompt) is equivalent to eval(raw_input(prompt)).

Key press and wait for a fixed amount of time

Here's a simple example using threads.

import threading
import time

# define a thread which takes input
class InputThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.user_input = None

def run(self):
self.user_input = input('input something: ')

def get_user_input(self):
return self.user_input

# main
it = InputThread()
it.start()
while True:
print('\nsleeping 1s and waiting for input... ')
time.sleep(1)
ui = it.get_user_input()
if ui != None:
print('The user input was', ui)
it = InputThread()
it.start()

How to make a script wait for a specific key press - Python 3

you can use keyboard.wait(), this wait function will wait until hotkey pressed (in our case 'e')...

while True:
start = time.time()
keyboard.wait("e")
end = time.time()
time_lapsed = end - start

In case you don't want to start with fresh time every loop, you can move start=time.time() out side of while loop

Wait until keys is pressed in Python

I saw some listeners in web and i found a code that solved my problem

from pynput import keyboard

def on_press(key):
if key == keyboard.Key.esc:
return False
try:
k = key.char
except:
k = key.name
if k == '[':
print('Key pressed: ' + k)
print('continuing...')
if k == ']':
print('Key pressed: ' + k)
print('stoping')
return False

Link: https://stackoverflow.com/a/43106497/15785950

Pause python script wait for key press

Use keyboard.read_key() as it will block the execution of the rest of code until a keyboard event happens, then returns that event's name or, if missing, its scan code.

import keyboard
import time

def mainmenu():
print ('1. Scan')
print ('2. Ping')
print ('3. Exit')

while(True):
a = keyboard.read_key()

if a == '1' or a == '2':
print("Option {} was pressed\n".format(a))
elif a == '3':
print("Exiting\n")
exit(0)
else:
print("None\n")
exit(0)

time.sleep(0.3)

mainmenu()


Related Topics



Leave a reply



Submit