Reacting to Keypress - python

So, I want to make some simple code with Python on Visual Studio Code where when I press Enter, it registers and adds one to a variable, like...
if Enter pressed:
variable += 1

Here is what I did using the keyboard module-
import keyboard
variable = 0
while True:
if keyboard.is_pressed("Enter"):
variable += 1
print(variable)
You may have to download keyboard. For this run this command in your computer's command prompt/terminal-
py -m pip install keyboard
There is probably a better way to do this using keyboard.on_press_key() , as using is_pressed adds 1 to variable continuously as long as the key is pressed.
Hope my answer helps!

import keyboard
variable = 0
print("Please Press Enter key")
def on_press_event(event):
global variable
if event.name == "enter":
variable += 1
print("pressed count %d times"%variable)
keyboard.on_press(on_press_event)
while True:
pass

Related

I am trying to develop a keyboard spammer and auto clicker but i cannot find anywhere a way to stop the spammer with a keybind

for now I'm just trying to get it to work with the keyboard spammer. So far I have done much searching but nothing seems to work.
if you have any tips on how to make the spamming stop without having to close the application it would be appreciated.
This is the code:
from typing import KeysView
import keyboard
import time
keyboard.wait("esc")
x = 4
while x != 5:
for i in range(9):
time.sleep(0.4)
print(keyboard.send("ctrl+v,enter"))
time.sleep(6)
(thanks)
Using the keyboard module there are many ways you could do this, one of them would be to add a hotkey that stops your loop via a global variable (in this example it's when you hit the spacebar):
from typing import KeysView
import keyboard
import time
keyboard.wait("esc")
running = True
def on_space():
global running
running = False
keyboard.add_hotkey('space', on_space)
while running:
for i in range(9):
time.sleep(0.4)
print(keyboard.send("ctrl+v,enter"))
time.sleep(6)
Adding a check for if a key is pressed inside of the for loop should do the trick. You could either make pressing the key break the loop, or since your loop waits for x to equal 5, you could simply make pressing the key change x to 5.

Input w/o enter in python

Is there a command for python shell that allows key input without using enter, like a tkinter bind or a cmd choice. any suggestions
I've tried a tkinter bind. pynput is not out for python 3.7 yet :(. any other suggestions? This did not work.
canvas.bind_all('<KeyPress-Left>',Left)
canvas.bind_all('<KeyPress-Right',Right)
def Right():
if R == 0:
X = X + 1
def Left():
if L == 0:
X = X - 1
I expected it to change x, but it didn't change.
(x is declared before these statements are called.)
use this if your os is windows
msvcrt.getch()
Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.
check --> https://docs.python.org/2/library/msvcrt.html

How to "continue" OR "exit" the program by pressing keys

Lets say I have 2 lines of code like this:
a = [1 , 2 , 3 , 4]
print (a)
Now I want to add something to this code to give the user 2 options:
1: press "Enter" to continue.
In this case the code should print "a"
2: press "Esc" to exit the program.
In this case the program should be stopped (e.g. exit the code).
I need to mention that I only want to use these 2 keys (Enter&Esc) NOT any key
I have been palying with raw_input and sys.exit but it did not work. Any idea how I can do it in this example?
Thanks!
You can use Keyboard module to detect keys pressed. It can be installed by using pip. You can find the documentation here. Keyboard API docs
pip install keyboard
check the below code to understand how it can be done.
import sys
import keyboard
a=[1,2,3,4]
print("Press Enter to continue or press Esc to exit: ")
while True:
try:
if keyboard.is_pressed('ENTER'):
print("you pressed Enter, so printing the list..")
print(a)
break
if keyboard.is_pressed('Esc'):
print("\nyou pressed Esc, so exiting...")
sys.exit(0)
except:
break
Output:

Code that recognises a keypress in Python 3

Is there anyway for python 3 to recognise a keypress? For example, if the user pressed the up arrow, the program would do one thing whereas if the down arrow was pressed, the program would do something else.
I do not mean the input() function where the user has to press enter after the keypress , I mean where the program recognises the keypress as some as it was pressed.
Is this question too confusing? xD
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
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('up'): #if key 'up' is pressed.You can use right,left,up,down and others
print('You Pressed A Key!')
break #finishing the loop
else:
pass
except:
break #if user pressed other than the given key the loop will break
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'):
#then do this
It Also Detect Key For The Whole Windows.
Thanks.
I assume this is a gui program,
If using the built-in gui module Tkinter, you can use bind to connect a function to a keypress.
main.bind('<Up>', userUpkey)
Where userUpKey is a function defined in the current scope.

How to break a for loop when pressing space bar?

I want to break an infinite loop when pressing space bar. I dont want to use Pygame, since it will produce a window.
How can i do it?
I got an answer. We can use msvcrt.kbhit() to detect a keypress. Here is the code i wrote.
import msvcrt
while 1:
print 'Testing..'
if msvcrt.kbhit():
if ord(msvcrt.getch()) == 32:
break
32 is the number for space. 27 for esc. like this we can choose any keys.
Important Note: This will not work in IDLE. Use terminal.
Python has a keyboard module with many features. You Can Use It In Both Shell and Console.
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(' '): #if key space is pressed.You can also use right,left,up,down and others like a,b,c,etc.
print('You Pressed A Key!')
break #finishing the loop
except:
pass
You can set it to multiple Key Detection:
if keyboard.is_pressed('up') or keyboard.is_pressed('down') or keyboard.is_pressed('left') or keyboard.is_pressed('right'):
#then do this
You Can Also Do Something like:
if keyboard.is_pressed('up') and keyboard.is_pressed('down'): #if both keys are pressed at the same time.
#then do this
Hope This Helps You.
Thanks.
Using space will be difficult because each system maps it differently. If you are okay with enter, this code will do the trick:
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print ("I'm doing stuff. Press Enter to stop me!")
print (i)
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = input()
break
i += 1
Source

Categories