How does keyboard.is_pressed() work in Python? - python

I'm trying to figure out when i press 'u' only 1 times, why is it pressing 'w' infinite times. Print functions don't work neither but if i delet the keyboard.press('w') and keyboard.release('w'), the print functions start to work correctly ( it's printing out 4 until i press a button then it prints out the right number and when i release the button it writes out 4 again)
while True:
if keyboard.is_pressed('u'):
keyboard.press('w')
keyboard.release('w')
print(0)
elif keyboard.is_pressed('j'):
#keyboard.press_and_release('s')
print(1)
elif keyboard.is_pressed('k'):
#keyboard.press_and_release('d')
print(2)
elif keyboard.is_pressed('h'):
#keyboard.press_and_release('a')
print(3)
else:
print(4)
keyboard.release('w')

I know that it was a year ago, but I have found this question today.
Sooo, according to the Keyboard API:
keyboard.press(hotkey) emulates pressing a hotkey on keyboard.
keyboard.release(hotkey) emulates releasing a hotkey on keyboard.
A hotkey is an key number, key name, or combination of two or more keys.
keyboard.press_and_release(hotkey) or keyboard.send(hotkey) emulates pressing and releasing a key or hotkey.
Pressing and releasing behaviour depends on values of do_press and do_release when using keyboard.send().
For example:
keyboard.send('space', do_press=True, do_release=True)
will emulate pressing and releasing space key, but:
keyboard.send('space', do_press=False, do_release=True)
will emulate only releasing space key.
keyboard.is_pressed(key) returns True if a specified key has been pressed, and False otherwise
Hope I've helped!

Related

Trying to accept the keyboard input 'R' alone or along side any other amount of keyboard inputs using either keyboard or pygame modules

import keyboard
import pygame
import mouse
import time
def press_X():
time.sleep(0.2)
keyboard.press('x')
time.sleep(0.6)
keyboard.release('x')
print('Command Executed - press_X')
#SA_R_X V_1.0
#------------------------------------------
while True:
try:
keyboard.add_hotkey('r', press_X)
time.sleep(0.5)
break
except:
keyboard.add_hotkey('r', press_X)
time.sleep(0.5)
break
the problem is the code cannot detect if 'r' is pressed when i am holding 'w' and/or 'space'... (well any key really)
I tried to use a try and except to handle a combination of any key + 'r'. But it did not work. All I need is for the code to be able to detect an 'r' input even if I am pressing/ holding another key at the same time. Then after this the code waits 0.2 seconds before holding down the 'x' key for 0.6 seconds and releasing. Any help is appreciated and it would be very helpful if you included a short explanation on where I went wrong and how you fixed it.
The documentation for this module can be found here. This is where all relevant information can be found.
The best way to do this, from my understanding, is to use an alternative function. If you want the program to continue to run, even though the key has not been pressed, then I suggest using the keyboard.on_press_key() function. This would mean that the rest of your program could still run, and your press_X() function could be run as a callback. Here is an example of how this code could be implemented.
import keyboard
import pygame
import mouse
import time
class App:
running = True
def press_X():
time.sleep(0.2)
keyboard.press('x')
time.sleep(0.6)
keyboard.release('x')
print('Command Executed - press_X')
App.running = False
#SA_R_X V_1.0
#------------------------------------------
keyboard.on_press_key('r', lambda x: press_X()) ## Adds an event listener for the r key
## This will stop execution if there is no code after this point
If you want it to stop the program and wait for the r key to be pressed, then you could use keyboard.wait(). This will basically pause your program until the key is pressed, after which your function would be run. For example, to replace the keyboard.on_press_key('r', lambda x: press_X()):
keyboard.wait('r')
press_X()
From my understanding, keyboard.add_hotkey() does not work in your situation because it is looking for an exact combination of keys being pressed, such as Ctrl+C, and will only go if only the keys in the hotkey are pressed.
I hope this helps, good luck!

How can i get it to increment and print whenever i press the key, not just once?

With the below program, whenever I press the "a" key, the keypresses variable increments by 1. The problem is, if I don't immediately let go fo the key, the keypresses variable continues to increment by 1.
How can I get it to increment (and print) whenever I press the key, ignoring the hold aspect?
import keyboard
keypresses = 0
while True:
if keyboard.is_pressed("a"):
keypresses = keypresses +1
print(keypresses)
print("A Key Pressed")
break
I understand that you want it so that pressing and holding only prints once (not indefinitely), and it will print again as long as the a key is released and pressed again.
Define a variable, pressing, to get if the key is still being pressed, or released:
import keyboard
keypresses = 0
pressing = False
while True:
if keyboard.is_pressed("a"):
if not pressing:
pressing = True
keypresses = keypresses +1
print(keypresses)
print("A Key Pressed")
else:
pressing = False
if you remove the break statement like this:
import keyboard
keypresses = 0
while True:
if keyboard.is_pressed("a"):
keypresses = keypresses +1
print(keypresses)
print("A Key Pressed")
break
this does not work, and when you run it, it is instantly finished the while cycle.
because the keyboard.is_pressed only detect now
and precisely because of this, which caused too many cpu
if you are in windows , you can use msvcrt to instead :-)
I'd remove the break statement.
On the Python docs you can see that break exits the innermost for/while loop, in your case the that loop would be the
while True:

Make broken loop run again? [duplicate]

This question already has answers here:
Detect if key was pressed once
(3 answers)
Closed 2 years ago.
I made a program which prints 'F pressed!' when i press the button 'F'. I don't want it to spam my console with that so I made the While-Loop break after that. How can I make the function run again and make the program not stop working? Or just make the text only appear once everytime I press the button?
import win32api
while True:
keystate = win32api.GetAsyncKeyState(0x46)
if keystate < 0:
print('F pressed!')
break
else:
pass
Thanks
How can I make the function run again and make the program not stop working?
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.
Therefore, you just remove break and everything is ok.
Or just make the text only appear once everytime I press the button?
If the least significant bit is set, the key was pressed after the
previous call to GetAsyncKeyState.
Try the code sample below:
import win32api
while True:
keystate = win32api.GetAsyncKeyState(0x46)&0x0001
if keystate > 0:
print('F pressed!')

How to keep pressing certain key for certain amount of time in python?

I am trying to automate android game using python but I end up in a situation where I have to keep pressing CTRL key and use mouse wheel to zoom out.
I installed Pynput and tried this command
keyboard.press('a')
time.sleep(3)
keyboard.release('a')
But it doesn't keep pressing a key for 3 seconds but press only once.
Can anyone pls tell me a simple script, where it will keep pressing CTRL key and use mouse wheel to zoom out?
I'm assuming you want the key to be pressed over and over again rather than being held down (which is what I think your code above is doing).
You got two options that I know of. The easiest, by far, is to use floats alongside sleep, and do something like this:
timer = 0
while timer < 3:
time.sleep(0.1)
timer += 0.1
keyboard.press('a')
This will press the 'a' key every 0.1 seconds until 3 seconds is reached.
Otherwise, you could import the 'threading' module which lets you run code in paralel, and therefore run a loop and a timer simultaneously. This is probably a huge can of worms for what you're trying to do. The code below presses the 'a' key as fast as possible until the three second timer ends, it doesn't exit threads or anything though, which is why this is probably a bad approach:
global_timer = 0
def keep_pressing_a():
while global_timer <= 3:
keyboard.press('a')
def count_to_three():
global global_timer
keep_counting = True
while keep_counting:
time.sleep(1)
global_timer += 1
if global_timer >= 3:
keep_counting = False
threading.Thread(target=count_to_three).start()
threading.Thread(target=something).start()

Unable To Break Out Of While Loop When Using Pynput.mouse

I have this relatively simple program that listens for mouse clicks and when the mouse button is held down prints "1"s. Unfortunately when I let go of the mouse it just keeps printing "1"s, even though there is an if statement which checks if the mouse is clicked and should stop the loop if it is not. I am using the pynput.mouse module for the mouse interaction.
Here is my code:
import time
from pynput.mouse import Listener
def clicked(x, y, button, pressed):
if pressed == True:
while button == button.left:
print("1")
time.sleep(1)
if pressed == False:
break
with Listener(on_click=clicked) as listener:
listener.join()
My theory is that once the loops starts it stops listening for mouse clicks, so it can never stop the loop. Would it be necessary to create a new thread for the loop? If yes, how would I do that?
Thanks!
Your current logic makes it impossible to get out of the loop, since pressed doesn't change within the loop. There is not a statement that checks if the mouse is clicked: your only if statements check whether the mouse was clicked when you entered the function. pressed doesn't change within the function.
Look at the critical logiic:
if pressed == True:
while ...
...
if pressed == False:
break
There is nothing in here to change the value of pressed; the first if guarantees that it's True anywhere within the loop.
Yes, you need to set up another listener that operates within the loop. You already know the building blocks: create a new one within the function and bind it to another operation that breaks the loop. For instance, you might "cheat" and have it reset pressed as a global variable.
You could also research how to do this in other answers, if you want an overall handler solution. keypress and keyrelease have been done often enough.
import pyautogui, random, time
import pynput
keys = ['w', 's', 'a', 'd']
def on_press(key):
p = True
if key == pynput.keyboard.Key.esc:
return False
else:
while p == True:
press = keys[random.randint(0,3)]
pyautogui.keyDown(press)
pyautogui.keyUp(press)
p = False
with pynput.keyboard.Listener(on_press=on_press) as L:
L.join()
a code like this will work instead of what you did.
BTW, that is just an example; feel free to visit my GitHub page: github.com/ironnicko

Categories

Resources