I have a for loop code in python that will detect a keypress
import keyboard
for x in range(100):
if keyboard.is_pressed('f4):
print('pressed')
but unfortunately, the code doesn't work with the for a loop.
I'd suggest to use a while loop because it is way more better for detecting the keypress and it loops the code forever until the condition is met.
while True:
if keyboard.is_pressed('f4'):
print('pressed')
You can use "wait"
import keyboard
for x in range(100):
keyboard.wait('f4')
print('pressed')
Related
I my python module keyboard commands are working fine as long as I don't have anything else in the infinite while loop.
As soon as I have something else in the while loop, the keyboard.is_pressed() does not work.
Can anyone explain why?
import keyboard
import time
while True:
if keyboard.is_pressed('a'):
print("/t/tThe 'a' key has been pressed")
time.sleep(0.1)
if keyboard.is_pressed('b'):
print("/t/tThe 'b' key has been pressed")
time.sleep(0.1)
if keyboard.is_pressed('q'):
print("/t/tThe 'q' key has been pressed")
break
for k in range(0,11,1):
print('k is at ' + str(k))
time.sleep(0.1)
print('DONE')
Ok. I got it. The problem is that the while loop runs very fast. So to explain the problem the thing is that when in any iteration of while loop your if statements will be processed with very fast speed but in your for loop you are printing 10 values with 0.1 sleep time each and hence spending 1 second in the for a loop. So for you to get the result of pressing key 'a' you have to press it in the very very split second when your for loops end and while loop starts which is not possible and hence the only solution is that you remove the for loop.
is_pressed() returns true only if the key is depressed right now.
If you press and release the key at normal speed, it's unlikely that it will be depressed during the few milliseconds when is_pressed() is called.
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.
I'm currently building a python code to play Blackjack where I need to be able to call certain functions uppon keypress without necessarily being in the terminal. I found this keyboard module which helped but I came across this issue.
def hit_or_stand(deck,hand):
global playing
print ("\nWould you like to Hit or Stand? Enter 'h' or 's'")
if keyboard.is_pressed('h'):
hit(deck,hand)
if keyboard.is_pressed('s'):
print("Player stands. Dealer is playing.")
playing = False
Let me explain what this function does as I don't want to overload everyone with the entire code. Essentially this function is called in a loop until the player decides to hit s which declares playing as False and therefore stopping the loop. If the player hits h then the hit function is called which draws a card. The player can draw as many cards.
My problem right now is that this code doesn't wait for user keypress. It loops extremely fast repeating it. I only want it to loop after either h or s is pressed.
I tried using keyboard.wait('h') on the line above the first if but then this doesn't allow the user to press s and therefore declare playing as False.
What I'm looking for is something along the lines of keyboard.wait('h'or's') but I know this does not work.
Thank you for your help. I am using python 3.7.9
EDIT: Keyboard Module I am referring too:
https://pypi.org/project/keyboard/
Use keyboard.read_key() to wait for any input.
If it's not h or s ,read_key again.
import keyboard
def mywait():
keyboard.read_key()
def my_function():
print("Hello")
def my_exit():
quit()
keyboard.add_hotkey("p", my_function)
keyboard.add_hotkey("esc", my_exit)
while True:
mywait()
I'm making this project for school that involves displaying data to a raspberry pi. The code I'm using refreshes (and needs to refresh) incredibly quickly, but I need a way for the user to stop the output, which I believe requires some kind of key event. The thing is, I'm new to Python and I can't figure out how to exit a while loop with turtle.onkey(). I found this code:
import turtle
def quit():
global more
more = False
turtle.onkey(quit, "Up")
turtle.listen()
more = True
while more:
print("something")
Which doesn't work. I've tested it. How do I make this work, or is there another way to get user input without interrupting the flow of the program?
while loop run on thread
check this code
import threading
def something():
while more:
print("something")
th = threading.Thread(something)
th.start()
Avoid infinite loops in a Python turtle graphics program:
more = True
while more:
print("something")
You can effectively block events from firing, including the one intended to stop the loop. Instead, use timer events to run your code and allow other events to fire:
from turtle import Screen
more = True
counter = 0
def stop():
global more
more = False
def start():
global more
more = True
screen.ontimer(do_something, 100)
def do_something():
global counter
print("something", counter)
counter += 1
if more:
screen.ontimer(do_something, 100)
screen = Screen()
screen.onkey(stop, "Up")
screen.onkey(start, "Down")
screen.listen()
start()
screen.mainloop()
I've added a counter to your program just so you can more easily see when the 'something' statements stop and I've added a restart on the down key so you can start them up again. Control should always reach mainloop() (or done() or exitonclick()) to give all the event handlers a chance to execute. Some infinite loops allow events to fire but they typically have calls into the turtle methods that allow it to have control some of the time but are still the wrong approach.
Chances are that you are trying to run your code in an interactive IPython shell. That does not work. The bare Python repl shell works, though.
Here I found a project that tries to bring turtle to IPython: https://github.com/Andrewkind/Turtle-Ipython. I did not test it, and I'm not exactly sure that this is a better solution than simply using the unsugared shell.
You could have you loop check a file like this:
def check_for_value_in_file():
with open('file.txt') as f:
value = f.read()
return value
while check_for_value_in_file() == 'the right value':
do_stuff()
I have a question about while loops in python.
I want to make a program that performs a while loop in a certain time.I want to add the extra feature that while the program us running,a certain variable can be changed by pressing a random key.
from time import sleep
import time
i=0
a=0
while i<10:
i=i+1
i=i+a
a=a+1
time.sleep(1)
print i
I want to do it that the variable a can be reset to 0 by pressing any key.The loop should continue unchanged if no button is pressed.What command should i add?
Thanks
Edit: I tried:
import pygame
from pygame.locals import *
import time
i=0
a=0
pygame.init()
while i<10:
pygame.event.get()
i=i+a
print i
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
i=0
i=i+1
time.sleep(1)
pygame.quit()
But now nothing happens when I press a button.What did i miss?
What you need is a non-blocking input function
while i<10:
keys = pygame.key.get_pressed()
etc
...
pygame has all sorts of event stuff built in so doing all the hard work of threading yourself shouldn't be necessary.
If that doesn't work for you check this out: http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/
You can use curses.Excellent doc is here:
http://docs.python.org/dev/howto/curses.html#user-input