Related
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.
Python has a keyboard module with many features. Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard # using module keyboard
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
break # if user pressed a key other than the given key the loop will break
For those who are on windows and were struggling to find an working answer here's mine: pynput
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
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:
from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be
#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
if current_window == desired_window_name:
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
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:
Using the function read_key():
import keyboard
while True:
if keyboard.read_key() == "p":
print("You pressed p")
break
This is gonna break the loop as the key p is pressed.
Method #2:
Using function wait:
import keyboard
keyboard.wait("p")
print("You pressed p")
It will wait for you to press p and continue the code as it is pressed.
Method #3:
Using the function on_press_key:
import keyboard
keyboard.on_press_key("p", lambda _:print("You pressed p"))
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:
keyboard.unhook_all()
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:
import keyboard
while True:
if keyboard.is_pressed("p"):
print("You pressed p")
break
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.
import keyboard
keyboard.record(until="p")
print("You pressed p")
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.
import curses
import os
def main(win):
win.nodelay(True)
key=""
win.clear()
win.addstr("Detected key:")
while 1:
try:
key = win.getkey()
win.clear()
win.addstr("Detected key:")
win.addstr(str(key))
if key == os.linesep:
break
except Exception as e:
# No input
pass
curses.wrapper(main)
For Windows you could use msvcrt like this:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print(key) # just to show the result
Use this code for find the which key pressed
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Use PyGame to have a window and then you can get the key events.
For the letter p:
import pygame, sys
import pygame.locals
pygame.init()
BLACK = (0,0,0)
WIDTH = 1280
HEIGHT = 1024
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
windowSurface.fill(BLACK)
while True:
for event in pygame.event.get():
if event.key == pygame.K_p: # replace the 'p' to whatever key you wanted to be pressed
pass #Do what you want to here
if event.type == pygame.locals.QUIT:
pygame.quit()
sys.exit()
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
import sys,tty,os,termios
def getkey():
old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
try:
while True:
b = os.read(sys.stdin.fileno(), 3).decode()
if len(b) == 3:
k = ord(b[2])
else:
k = ord(b)
key_mapping = {
127: 'backspace',
10: 'return',
32: 'space',
9: 'tab',
27: 'esc',
65: 'up',
66: 'down',
67: 'right',
68: 'left'
}
return key_mapping.get(k, chr(k))
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
try:
while True:
k = getkey()
if k == 'esc':
quit()
else:
print(k)
except (KeyboardInterrupt, SystemExit):
os.system('stty sane')
print('stopping.')
Non-root version that works even through ssh: sshkeyboard. Install with pip install sshkeyboard,
then write script such as:
from sshkeyboard import listen_keyboard
def press(key):
print(f"'{key}' pressed")
def release(key):
print(f"'{key}' released")
listen_keyboard(
on_press=press,
on_release=release,
)
And it will print:
'a' pressed
'a' released
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:
import tkinter as tk
def key_handler(event=None):
if event and event.keysym in ('s', 'p'):
'do something'
r = tk.Tk()
t = tk.Text()
t.pack()
r.bind('<Key>', key_handler)
r.mainloop()
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:
import msvcrt
def _secret_key(self):
# Get the key pressed by the user and check if he/she wins.
bk = chr(10) + "-"*25 + chr(10)
while True:
print(bk + "Press any key(s)" + bk)
#asks the user to type any key(s)
kp = str(msvcrt.getch()).replace("b'", "").replace("'", "")
# Store key's value.
if r'\xe0' in kp:
kp += str(msvcrt.getch()).replace("b'", "").replace("'", "")
# Refactor the variable in case of multi press.
if kp == r'\xe0\x8a':
# If user pressed the secret key, the game ends.
# \x8a is CTRL+F12, that's the secret key.
print(bk + "CONGRATULATIONS YOU PRESSED THE SECRET KEYS!\a" + bk)
print("Press any key to exit the game")
msvcrt.getch()
break
else:
print(" You pressed:'", kp + "', that's not the secret key(s)\n")
if self.select_continue() == "n":
if self.secondary_options():
self._main_menu()
break
If you want the full source code of the program you can see it or download it from GitHub
The secret keypress is:
Ctrl+F12
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.
Install it:
pip install getkey
And use it:
from getkey import getkey
while True: #Breaks when key is pressed
key = getkey()
print(key) #Optionally prints out the key.
break
We can add this in a function to return the pressed key.
def Ginput(str):
"""
Now, this function is like the native input() function. It can accept a prompt string, print it out, and when one key is pressed, it will return the key to the caller.
"""
print(str, end='')
while True:
key = getkey()
print(key)
return key
Use like this:
inp = Ginput("\n Press any key to continue: ")
print("You pressed " + inp)
import cv2
key = cv2.waitKey(1)
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:
import curses
screen = curses.initscr()
curses.noecho()
curses.cbreak()
screen.keypad(True)
try:
while True:
char = screen.getch()
if char == ord('q'):
break
elif char == curses.KEY_UP:
print('up')
elif char == curses.KEY_DOWN:
print('down')
elif char == curses.KEY_RIGHT:
print('right')
elif char == curses.KEY_LEFT:
print('left')
elif char == ord('s'):
print('stop')
finally:
curses.nocbreak(); screen.keypad(0); curses.echo()
curses.endwin()
Here is a cross-platform solution, both blocking and non-blocking, not requiring any external libraries:
import contextlib as _contextlib
try:
import msvcrt as _msvcrt
# Length 0 sequences, length 1 sequences...
_ESCAPE_SEQUENCES = [frozenset(("\x00", "\xe0"))]
_next_input = _msvcrt.getwch
_set_terminal_raw = _contextlib.nullcontext
_input_ready = _msvcrt.kbhit
except ImportError: # Unix
import sys as _sys, tty as _tty, termios as _termios, \
select as _select, functools as _functools
# Length 0 sequences, length 1 sequences...
_ESCAPE_SEQUENCES = [
frozenset(("\x1b",)),
frozenset(("\x1b\x5b", "\x1b\x4f"))]
#_contextlib.contextmanager
def _set_terminal_raw():
fd = _sys.stdin.fileno()
old_settings = _termios.tcgetattr(fd)
try:
_tty.setraw(_sys.stdin.fileno())
yield
finally:
_termios.tcsetattr(fd, _termios.TCSADRAIN, old_settings)
_next_input = _functools.partial(_sys.stdin.read, 1)
def _input_ready():
return _select.select([_sys.stdin], [], [], 0) == ([_sys.stdin], [], [])
_MAX_ESCAPE_SEQUENCE_LENGTH = len(_ESCAPE_SEQUENCES)
def _get_keystroke():
key = _next_input()
while (len(key) <= _MAX_ESCAPE_SEQUENCE_LENGTH and
key in _ESCAPE_SEQUENCES[len(key)-1]):
key += _next_input()
return key
def _flush():
while _input_ready():
_next_input()
def key_pressed(key: str = None, *, flush: bool = True) -> bool:
"""Return True if the specified key has been pressed
Args:
key: The key to check for. If None, any key will do.
flush: If True (default), flush the input buffer after the key was found.
Return:
boolean stating whether a key was pressed.
"""
with _set_terminal_raw():
if key is None:
if not _input_ready():
return False
if flush:
_flush()
return True
while _input_ready():
keystroke = _get_keystroke()
if keystroke == key:
if flush:
_flush()
return True
return False
def print_key() -> None:
"""Print the key that was pressed
Useful for debugging and figuring out keys.
"""
with _set_terminal_raw():
_flush()
print("\\x" + "\\x".join(map("{:02x}".format, map(ord, _get_keystroke()))))
def wait_key(key=None, *, pre_flush=False, post_flush=True) -> str:
"""Wait for a specific key to be pressed.
Args:
key: The key to check for. If None, any key will do.
pre_flush: If True, flush the input buffer before waiting for input.
Useful in case you wish to ignore previously pressed keys.
post_flush: If True (default), flush the input buffer after the key was
found. Useful for ignoring multiple key-presses.
Returns:
The key that was pressed.
"""
with _set_terminal_raw():
if pre_flush:
_flush()
if key is None:
key = _get_keystroke()
if post_flush:
_flush()
return key
while _get_keystroke() != key:
pass
if post_flush:
_flush()
return key
You can use key_pressed() inside a while loop:
while True:
time.sleep(5)
if key_pressed():
break
You can also check for a specific key:
while True:
time.sleep(5)
if key_pressed("\x00\x48"): # Up arrow key on Windows.
break
Find out special keys using print_key():
>>> print_key()
# Press up key
\x00\x48
Or wait until a certain key is pressed:
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
You can use pygame's get_pressed():
import pygame
while True:
keys = pygame.key.get_pressed()
if (keys[pygame.K_LEFT]):
pos_x -= 5
elif (keys[pygame.K_RIGHT]):
pos_x += 5
elif (keys[pygame.K_UP]):
pos_y -= 5
elif (keys[pygame.K_DOWN]):
pos_y += 5
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,
while True:
if keyboard.is_pressed("down"):
print("Reach the bottom!")
if keyboard.is_pressed("up"):
print("Reach the top!")
if keyboard.is_pressed("ctrl+c"):
break
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()
while True:
if keyboard.is_pressed("down"):
print("Reach the bottom!")
time.sleep(0.5)
if keyboard.is_pressed("up"):
print("Reach the top!")
time.sleep(0.5)
if keyboard.is_pressed("ctrl+c"):
break
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.
while True:
# Wait for the next event.
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN and event.name == 'down':
# do whatever function you wanna here
if event.event_type == keyboard.KEY_DOWN and event.name == 'up':
# do whatever function you wanna here
if keyboard.is_pressed("ctrl+c"):
break
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!
Thank you, wish you have a great day ahead!
This question already has answers here:
Why does sys.exit() not exit when called inside a thread in Python?
(6 answers)
Closed 1 year ago.
I wrote a script that can draw polylines (it over on github) from ScalableVectorGraphics(.svg) by moving the Mouse accordingly.
When you are handing the control over your mouse to a script, a killswitch is certainly necessary, so I found an example for a Keyboard listener somwhere on the Internet:
def on_press(key):
try:
sys.exit()
print('alphanumeric key {0} pressed'.format(key.char))
print('adsfadfsa')
except AttributeError:
print('special key {0} pressed'.format(
key))
def main():
listener = keyboard.Listener( #TODO fix sys.exit()
on_press=on_press)
listener.start()
if __name__ == '__main__':
main()
It seems to be working: If i add a a print statement before the sys.exit() it is instantly executed properly.
But with sys.exit() it keeps moving my mouse and the python interpreter is still on Taskmanager. I don't know why it keeps executing.
Thank you in advance for your suggestions.
MrSmoer
Solution was: os._exit(1)
Full Sourcecode:
from pynput import mouse as ms
from pynput import keyboard
from pynput.mouse import Button, Controller
import threading
import time
from xml.dom import minidom
import re
sys.path.append('/Users/MrSmoer/Desktop/linedraw-master')
mouse = ms.Controller()
tlc = None
brc = None
brc_available = threading.Event()
biggestY = 0
biggestX = 0
drwblCnvsX = 0
drwblCnvsY = 0
def on_click(x, y, button, pressed):
if not pressed:
# Stop listener
return False
def on_press(key):
try:
sys.exit()
print('alphanumeric key {0} pressed'.format(key.char))
print('adsfadfsa')
except AttributeError:
print('special key {0} pressed'.format(
key))
def initialize():
print("Please select your programm and then click at the two corners of the canvas. Press any key to cancel.")
with ms.Listener(
on_click=on_click) as listener:
listener.join()
print('please middleclick, when you are on top left corner of canvas')
with ms.Listener(
on_click=on_click) as listener:
listener.join()
global tlc
tlc = mouse.position
print('please middleclick, when you are on bottom left corner of canvas')
with ms.Listener(
on_click=on_click) as listener:
listener.join()
global brc
brc = mouse.position
mouse.position = tlc
print('thread finished')
brc_available.set()
def getDrawabableCanvasSize(polylines):
global biggestX
global biggestY
for i in range(len(polylines)): # goes throug all polylines
points = hyphen_split(polylines[i]) # Splits polylines to individual points
for c in range(len(points)): # goes throug all points on polyline
cord = points[c].split(',') # splits points in x and y axis
if float(cord[0]) > (biggestX - 5):
biggestX = float(cord[0]) + 5
if float(cord[1]) > (biggestY - 5):
biggestY = float(cord[1]) + 5
print('TLC: ', tlc)
print('bigX: ', biggestX)
print('bigY: ', biggestY)
cnvswidth = tuple(map(lambda i, j: i - j, brc, tlc))[0]
cnvsheight = tuple(map(lambda i, j: i - j, brc, tlc))[1]
cnvsapr = cnvswidth / cnvsheight
print('Canvasaspr: ', cnvsapr)
drwblcnvaspr = biggestX / biggestY
print('drwnble aspr: ', drwblcnvaspr)
if drwblcnvaspr < cnvsapr: # es mus h vertikal saugend
print('es mus h vertikal saugend')
finalheight = cnvsheight
finalwidth = finalheight * drwblcnvaspr
else: # es muss horizontal saugend, oder aspect ratio ist eh gleich
print('es muss horizontal saugend, oder aspect ratio ist eh gleich')
finalwidth = cnvswidth
scalefactor = finalwidth / biggestX
print(scalefactor)
return scalefactor
def drawPolyline(polyline, scalefactor):
points = hyphen_split(polyline)
#print(points)
beginpoint = tlc
for c in range(len(points)): # goes throug all points on polyline
beginpoint = formatPoint(points[c], scalefactor)
if len(points) > c + 1:
destpoint = formatPoint(points[c + 1], scalefactor)
mouse.position = beginpoint
time.sleep(0.001)
mouse.press(Button.left)
# time.sleep(0.01)
mouse.position = destpoint
# time.sleep(0.01)
mouse.release(Button.left)
else:
destpoint = tlc
#print("finished line")
mouse.release(Button.left)
def formatPoint(p, scale):
strcord = p.split(',')
#print(scale)
#print(tlc)
x = float(strcord[0]) * scale + tlc[0] # + drwblCnvsX/2
y = float(strcord[1]) * scale + tlc[1] # + drwblCnvsY/2
#print('x: ', x)
#print('y: ', y)
thistuple = (int(x), int(y))
return thistuple
def hyphen_split(a):
return re.findall("[^,]+\,[^,]+", a)
# ['id|tag1', 'id|tag2', 'id|tag3', 'id|tag4']
def main():
listener = keyboard.Listener( #TODO fix sys.exit()
on_press=on_press)
listener.start()
thread = threading.Thread(target=initialize()) #waits for initializing function (two dots)
thread.start()
brc_available.wait()
# print(sys.argv[1])
doc = minidom.parse('/Users/MrSmoer/Desktop/linedraw-master/output/out.svg') # parseString also exists
try:
if sys.argv[1] == '-ip':
doc = minidom.parse(sys.argv[2])
except IndexError:
print('Somethings incorrect1')
polylines = NotImplemented
try:
doc = minidom.parse('/Users/MrSmoer/Desktop/linedraw-master/output/out.svg') # parseString also exists
# /Users/MrSmoer/Desktop/linedraw-master/output/output2.svg
#doc = minidom.parse('/Users/MrSmoer/Desktop/Test.svg')
polylines = [path.getAttribute('points') for path
in doc.getElementsByTagName('polyline')]
doc.unlink()
except:
print('Somethings incorrect3')
# print(polylines)
scalefactor = getDrawabableCanvasSize(polylines)
for i in range(len(polylines)):
drawPolyline(polylines[i], scalefactor)
if __name__ == '__main__':
main()
Sometimes, when writing a multithreadded app, raise SystemExit and sys.exit() both kills only the running thread. On the other hand, os._exit() exits the whole process.
While you should generally prefer sys.exit because it is more "friendly" to other code, all it actually does is raise an exception.
If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch SystemExit, there is another function - os._exit - which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter
A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.
Example:
#do stuff
if this == that:
quit()
You may try these options!!
Hope it works fine!! If not tell us, we will try more solutions!
That sys.exit() ends up killing the thread that it's executing it, but you program seems to take advantage of multiple threads.
You will need to kill all the threads of the program including the main one if you want to exit.
I want to create a tool which will allow me to use some of the Vim-style commands in an application (Scrivener) that does not support it.
For example, if
the current mode is Command mode and
the user presses the button w,
then, the caret should move one character to the right. Instead of the w character, Scrivener should receive the "right arrow" signal.
To implement this, I wrote the following code (based on these 2 answers: 1, 2):
from pynput.keyboard import Key, Listener, Controller
from typing import Optional
from ctypes import wintypes, windll, create_unicode_buffer
def getForegroundWindowTitle() -> Optional[str]:
hWnd = windll.user32.GetForegroundWindow()
length = windll.user32.GetWindowTextLengthW(hWnd)
buf = create_unicode_buffer(length + 1)
windll.user32.GetWindowTextW(hWnd, buf, length + 1)
if buf.value:
return buf.value
else:
return None
class State:
def __init__(self):
self.mode = "Command"
state = State()
keyboard = Controller()
def on_press(key):
pass
def on_release(key):
if key == Key.f12:
return False
window_title = getForegroundWindowTitle()
if not window_title.endswith("Scrivener"):
return
print("Mode: " + state.mode)
print('{0} release'.format(
key))
if state.mode == "Command":
print("1")
if str(key) == "'w'":
print("2")
print("w released in command mode")
# Press the backspace button to delete the w letter
keyboard.press(Key.backspace)
# Press the right arrow button
keyboard.press(Key.right)
if key == Key.insert:
if state.mode == "Command":
state.mode = "Insert"
else:
state.mode = "Command"
# Collect events until released
print("Press F12 to exit")
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Whenever I press the button w in Scrivener in Command mode, two keystrokes are sent to Scrivener:
Backspace to delete the already typed w character.
Right arrow to move the caret.
This kinda works, but you can see the w character being displayed and deleted again (see this video).
How can I make sure that the keystroke with w does not reach Scrivener at all, if the mode is Command and currently focused window is the Scrivener application?
First you need to install pyHook and pywin32 library.
Then monitor the keyboard information through pyhook. If you need to intercept the keyboard information (for example, press w), return False.
Finally, through pythoncom.PumpMessages () to achieve loop monitoring.
Here is the sample:
import pyHook
import pythoncom
from pynput.keyboard import Key, Listener, Controller
keyboard = Controller()
def onKeyboardEvent(event):
if event.Key == "F12":
exit()
print("1")
if event.Key == 'W':
print("2")
print("w released in command mode")
# Press the right arrow button
keyboard.press(Key.right)
return False
print("hook" + event.Key)
return True
# Collect events until released
print("Press F12 to exit")
hm = pyHook.HookManager()
hm.KeyDown = onKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
I started a little backdoor and i use a keylogger in it.
I use the pynput library and i wanted to know if it's possible to stop the pynput listener from an outside function or in the main loop.
Here is a code snippet :
class KeyLoggerThread(threading.Thread):
global Quit
def __init__(self):
super().__init__()
def run(self):
logging.basicConfig(filename="keys.log",level=logging.DEBUG, format='%(asctime)s %(message)s')
def on_press(key):
logging.debug(str(key))
if key == Key.esc:
return False
with Listener(on_press = on_press) as listener:
listener.join()
Right now, i have to use the esc key with is not very practical due to the fact that this keylogger is used in my backdoor so when the victim press esc it quit the keylogger.
What i really want is to send a signal whenever i want to stop it (not from a key).
Thanks in advance, have a nice day !
You talk about keylogger... yeah, if you want a signal but not from a key then buy a remoter :))
In this sample code I maked a combo of 3 different things for password to not close listener events by mistake.
Hold middle/wheel mouse button, write a word ex.#admin (tap that key characters) and make shore you hade some text copyed... PS. I do not know to many peoples who write on keyboard with hand on mouse and holding the weel in the same time... That is just an example, be creative.
#// IMPORTS
import pyperclip
from pynput import keyboard, mouse
keylogger_stop = False
# password = [Boolean, String_1, String_2]
# Boolean - Need to hold mouse middle mutton, if you
# released befoure to finish, well try again
# String_1 - Write that password/word. Special keys
# are ignored (alt, ctrl, cmd, shift etc.)
# String 2 - You need to have this text copyed (Ctrl + C)
# and after you finish to write manual String_1
password = [False, "#dmin", ">> Double $$$ check! <<"]
pass_type = ""
class Keylogger:
def __init__(self):
Keylogger.Keyboard.Listener()
Keylogger.Mouse.Listener()
class Keyboard:
def Press(key):
if keylogger_stop == True: return False
else: print(f"K_K_P: {key}")
def Release(key):
global pass_type, keylogger_stop
# get copyed string + holding right mouse button pressed
if password[0] == True and pass_type == password[1]:
if pyperclip.paste().strip() == password[2]: keylogger_stop = True
else: password[0] = False; pass_type = ""
# write string password/word + holding right mouse button pressed
elif password[0] == True:
try: pass_type += key.char; print(pass_type, password[0])
except: pass
else: print(f"K_K_R: {key}")
def Listener():
l = keyboard.Listener(on_press = Keylogger.Keyboard.Press,
on_release = Keylogger.Keyboard.Release)
l.start()
class Mouse:
def Click(x, y, b, p):
global pass_type
if keylogger_stop == True: return False
# hold mouse button pressed, on release will reset the progress
elif b == mouse.Button.middle:
if p == True: password[0] = True
else: password[0] = False; pass_type = ""
else: print(f"{b} was {'pressed' if p else 'released'} at ({x} x {y})")
def Listener():
mouse.Listener(on_click = Keylogger.Mouse.Click).start()
class Main:
def __init__(self):
Keylogger()
#// RUN IF THIS FILE IS THE MAIN ONE
if __name__ == "__main__":
Main()
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.
Python has a keyboard module with many features. Install it, perhaps with this command:
pip3 install keyboard
Then use it in code like:
import keyboard # using module keyboard
while True: # making a loop
try: # used try so that if user pressed other than the given key error will not be shown
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
break # finishing the loop
except:
break # if user pressed a key other than the given key the loop will break
For those who are on windows and were struggling to find an working answer here's mine: pynput
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
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:
from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be
#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
if current_window == desired_window_name:
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
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:
Using the function read_key():
import keyboard
while True:
if keyboard.read_key() == "p":
print("You pressed p")
break
This is gonna break the loop as the key p is pressed.
Method #2:
Using function wait:
import keyboard
keyboard.wait("p")
print("You pressed p")
It will wait for you to press p and continue the code as it is pressed.
Method #3:
Using the function on_press_key:
import keyboard
keyboard.on_press_key("p", lambda _:print("You pressed p"))
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:
keyboard.unhook_all()
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:
import keyboard
while True:
if keyboard.is_pressed("p"):
print("You pressed p")
break
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.
import keyboard
keyboard.record(until="p")
print("You pressed p")
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.
import curses
import os
def main(win):
win.nodelay(True)
key=""
win.clear()
win.addstr("Detected key:")
while 1:
try:
key = win.getkey()
win.clear()
win.addstr("Detected key:")
win.addstr(str(key))
if key == os.linesep:
break
except Exception as e:
# No input
pass
curses.wrapper(main)
For Windows you could use msvcrt like this:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print(key) # just to show the result
Use this code for find the which key pressed
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
Use PyGame to have a window and then you can get the key events.
For the letter p:
import pygame, sys
import pygame.locals
pygame.init()
BLACK = (0,0,0)
WIDTH = 1280
HEIGHT = 1024
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
windowSurface.fill(BLACK)
while True:
for event in pygame.event.get():
if event.key == pygame.K_p: # replace the 'p' to whatever key you wanted to be pressed
pass #Do what you want to here
if event.type == pygame.locals.QUIT:
pygame.quit()
sys.exit()
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
import sys,tty,os,termios
def getkey():
old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
try:
while True:
b = os.read(sys.stdin.fileno(), 3).decode()
if len(b) == 3:
k = ord(b[2])
else:
k = ord(b)
key_mapping = {
127: 'backspace',
10: 'return',
32: 'space',
9: 'tab',
27: 'esc',
65: 'up',
66: 'down',
67: 'right',
68: 'left'
}
return key_mapping.get(k, chr(k))
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
try:
while True:
k = getkey()
if k == 'esc':
quit()
else:
print(k)
except (KeyboardInterrupt, SystemExit):
os.system('stty sane')
print('stopping.')
Non-root version that works even through ssh: sshkeyboard. Install with pip install sshkeyboard,
then write script such as:
from sshkeyboard import listen_keyboard
def press(key):
print(f"'{key}' pressed")
def release(key):
print(f"'{key}' released")
listen_keyboard(
on_press=press,
on_release=release,
)
And it will print:
'a' pressed
'a' released
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:
import tkinter as tk
def key_handler(event=None):
if event and event.keysym in ('s', 'p'):
'do something'
r = tk.Tk()
t = tk.Text()
t.pack()
r.bind('<Key>', key_handler)
r.mainloop()
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:
import msvcrt
def _secret_key(self):
# Get the key pressed by the user and check if he/she wins.
bk = chr(10) + "-"*25 + chr(10)
while True:
print(bk + "Press any key(s)" + bk)
#asks the user to type any key(s)
kp = str(msvcrt.getch()).replace("b'", "").replace("'", "")
# Store key's value.
if r'\xe0' in kp:
kp += str(msvcrt.getch()).replace("b'", "").replace("'", "")
# Refactor the variable in case of multi press.
if kp == r'\xe0\x8a':
# If user pressed the secret key, the game ends.
# \x8a is CTRL+F12, that's the secret key.
print(bk + "CONGRATULATIONS YOU PRESSED THE SECRET KEYS!\a" + bk)
print("Press any key to exit the game")
msvcrt.getch()
break
else:
print(" You pressed:'", kp + "', that's not the secret key(s)\n")
if self.select_continue() == "n":
if self.secondary_options():
self._main_menu()
break
If you want the full source code of the program you can see it or download it from GitHub
The secret keypress is:
Ctrl+F12
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.
Install it:
pip install getkey
And use it:
from getkey import getkey
while True: #Breaks when key is pressed
key = getkey()
print(key) #Optionally prints out the key.
break
We can add this in a function to return the pressed key.
def Ginput(str):
"""
Now, this function is like the native input() function. It can accept a prompt string, print it out, and when one key is pressed, it will return the key to the caller.
"""
print(str, end='')
while True:
key = getkey()
print(key)
return key
Use like this:
inp = Ginput("\n Press any key to continue: ")
print("You pressed " + inp)
import cv2
key = cv2.waitKey(1)
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:
import curses
screen = curses.initscr()
curses.noecho()
curses.cbreak()
screen.keypad(True)
try:
while True:
char = screen.getch()
if char == ord('q'):
break
elif char == curses.KEY_UP:
print('up')
elif char == curses.KEY_DOWN:
print('down')
elif char == curses.KEY_RIGHT:
print('right')
elif char == curses.KEY_LEFT:
print('left')
elif char == ord('s'):
print('stop')
finally:
curses.nocbreak(); screen.keypad(0); curses.echo()
curses.endwin()
Here is a cross-platform solution, both blocking and non-blocking, not requiring any external libraries:
import contextlib as _contextlib
try:
import msvcrt as _msvcrt
# Length 0 sequences, length 1 sequences...
_ESCAPE_SEQUENCES = [frozenset(("\x00", "\xe0"))]
_next_input = _msvcrt.getwch
_set_terminal_raw = _contextlib.nullcontext
_input_ready = _msvcrt.kbhit
except ImportError: # Unix
import sys as _sys, tty as _tty, termios as _termios, \
select as _select, functools as _functools
# Length 0 sequences, length 1 sequences...
_ESCAPE_SEQUENCES = [
frozenset(("\x1b",)),
frozenset(("\x1b\x5b", "\x1b\x4f"))]
#_contextlib.contextmanager
def _set_terminal_raw():
fd = _sys.stdin.fileno()
old_settings = _termios.tcgetattr(fd)
try:
_tty.setraw(_sys.stdin.fileno())
yield
finally:
_termios.tcsetattr(fd, _termios.TCSADRAIN, old_settings)
_next_input = _functools.partial(_sys.stdin.read, 1)
def _input_ready():
return _select.select([_sys.stdin], [], [], 0) == ([_sys.stdin], [], [])
_MAX_ESCAPE_SEQUENCE_LENGTH = len(_ESCAPE_SEQUENCES)
def _get_keystroke():
key = _next_input()
while (len(key) <= _MAX_ESCAPE_SEQUENCE_LENGTH and
key in _ESCAPE_SEQUENCES[len(key)-1]):
key += _next_input()
return key
def _flush():
while _input_ready():
_next_input()
def key_pressed(key: str = None, *, flush: bool = True) -> bool:
"""Return True if the specified key has been pressed
Args:
key: The key to check for. If None, any key will do.
flush: If True (default), flush the input buffer after the key was found.
Return:
boolean stating whether a key was pressed.
"""
with _set_terminal_raw():
if key is None:
if not _input_ready():
return False
if flush:
_flush()
return True
while _input_ready():
keystroke = _get_keystroke()
if keystroke == key:
if flush:
_flush()
return True
return False
def print_key() -> None:
"""Print the key that was pressed
Useful for debugging and figuring out keys.
"""
with _set_terminal_raw():
_flush()
print("\\x" + "\\x".join(map("{:02x}".format, map(ord, _get_keystroke()))))
def wait_key(key=None, *, pre_flush=False, post_flush=True) -> str:
"""Wait for a specific key to be pressed.
Args:
key: The key to check for. If None, any key will do.
pre_flush: If True, flush the input buffer before waiting for input.
Useful in case you wish to ignore previously pressed keys.
post_flush: If True (default), flush the input buffer after the key was
found. Useful for ignoring multiple key-presses.
Returns:
The key that was pressed.
"""
with _set_terminal_raw():
if pre_flush:
_flush()
if key is None:
key = _get_keystroke()
if post_flush:
_flush()
return key
while _get_keystroke() != key:
pass
if post_flush:
_flush()
return key
You can use key_pressed() inside a while loop:
while True:
time.sleep(5)
if key_pressed():
break
You can also check for a specific key:
while True:
time.sleep(5)
if key_pressed("\x00\x48"): # Up arrow key on Windows.
break
Find out special keys using print_key():
>>> print_key()
# Press up key
\x00\x48
Or wait until a certain key is pressed:
>>> wait_key("a") # Stop and ignore all inputs until "a" is pressed.
You can use pygame's get_pressed():
import pygame
while True:
keys = pygame.key.get_pressed()
if (keys[pygame.K_LEFT]):
pos_x -= 5
elif (keys[pygame.K_RIGHT]):
pos_x += 5
elif (keys[pygame.K_UP]):
pos_y -= 5
elif (keys[pygame.K_DOWN]):
pos_y += 5
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,
while True:
if keyboard.is_pressed("down"):
print("Reach the bottom!")
if keyboard.is_pressed("up"):
print("Reach the top!")
if keyboard.is_pressed("ctrl+c"):
break
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()
while True:
if keyboard.is_pressed("down"):
print("Reach the bottom!")
time.sleep(0.5)
if keyboard.is_pressed("up"):
print("Reach the top!")
time.sleep(0.5)
if keyboard.is_pressed("ctrl+c"):
break
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.
while True:
# Wait for the next event.
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN and event.name == 'down':
# do whatever function you wanna here
if event.event_type == keyboard.KEY_DOWN and event.name == 'up':
# do whatever function you wanna here
if keyboard.is_pressed("ctrl+c"):
break
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!
Thank you, wish you have a great day ahead!