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
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 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')
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 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