Pause and Continue a Loop When Press Key in Python - python

Who can help me on this?
Pause Countdown when press "P" Key and continue the Countdown when press "S" key. Until now i have this code, but i cant find the way to solve this.
Thanks
from multiprocessing import Process
import keyboard
import time
def countdown_1():
i=6
j=40
k=0
while True:
a = keyboard.read_key()
if(str(a) != "p"):
if(j==-1):
j=59
i -=1
if(j > 9):
print(str(k)+str(i)+":"+str(j))
else:
print(str(k)+str(i)+":"+str(k)+str(j))
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print("END")
time.sleep(1)
countdown_1()

I get a solution to your problem, that is because when you use keyboard.readkey() python wait for a key to be pressed. instead, you should use keyboard.is_pressed('X')
I have modified your code to make a working version, I slightly change it to match my taste.
from multiprocessing import Process
import keyboard
import time
def countdown_1():
pause_keyboard = False # I use a bolean as a state is clearer for me
i = 6 # minutes
j = 40
k = 0 # represent 0 we will instead use code format
while True:
starting_time = time.time()
while True: # this loop wait one second or slightly more
if time.time() - starting_time >= 1: # a second or more
break
if keyboard.is_pressed('p'):
pause_keyboard = True
elif keyboard.is_pressed('s'):
pause_keyboard = False
if pause_keyboard:
continue
if (j == -1): ## here we adjust the count when we changes minutes
j = 59 # 59 secondes
i -= 1 # one minutes less
if(j > 9): ## in order to pretty print
print("{}{}:{}".format(0, i, j)) # you can direclty use 0 instead of k.
else:
print("{}{}:{}{}".format(0, i, 0, j))
j -= 1
if(i==0 and j==-1): # we finish the counter
break
if(i==0 and j==-1):
print("END")
time.sleep(1) # wait a last second
countdown_1()
EDIT: Use time.time() instead of sleep to be able to catch signals.

Related

(Python) How to listen to keyboard while doing other things in a while loop

Here is my code.
import keyboard
while num <= total_num_list-1:
show_num = num + 1
duration_in_min = 1:30
t = 1
while t <= duration:
if keyboard.is_pressed("n"):
break
time.sleep(1)
time_in_min = time.strftime('%M:%S', time.gmtime(t))
print(f"{time_in_min}/{duration_in_min}")
t += 1
num += 1
This code is working for now, but it needs me to hold the "n" key to break the loop because of the delay. What I want is it to have a immediate respond to my key press. What modules can I use or what should I do to make it work?
I am a beginner, sorry if there is any mistakes.

How do i do some stuff and count time in parallel in python?

I want my code to take some integers for some time (e.g. 10 seconds) and to count and print time every second. So it prints time permanently and i enter some numbers whenever i want. Maybe i should use async functions?
def accepting_bets():
global list_of_bets
list_of_bets = []
list_of_bets.append(int(input()))
def main():
i = 10
while True:
print(f"{i} seconds remaining...")
time.sleep(1)
i -= 1
accepting_bets()
if i == 0:
break
print(list_of_bets)
You can move the timing code to a different thread.
I would recommend researching about multi-threading in Python if you aren't aware about it.
import threading
import time
def countTime():
i = 10
while True:
print(f"{i} seconds remaining...")
time.sleep(1)
i -= 1
if i == 0:
break
print(list_of_bets)
thread1 = threading.Thread(target=countTime)
thread1.start()
# while you want to get the input
global list_of_bets
list_of_bets = []
list_of_bets.append(int(input()))
The countTime function will keep on running on another thread, and will not be paused by the input statement

A timer that restarts on a trigger Python - how to restart?

Bit of a newbie so bear with:
I am trying to make a crude 60s timer that is reset and starts again on the rising edge of a trigger (ie when a gate goes high). The problem I have is that it won't reset and restart unless the timer has completed (ie reached zero). How do I interrupt the while loop and get it to start again?
Here is my code:
import keyboard
import time
t=60
last = False
current = False
while True:
current = keyboard.is_pressed('space') # triggered when space bar is pressed
if last == 0 and current == 1:
while t>=0:
print(t)
t-=1
time.sleep(1)
last = current # reset
Try this:
import time
import keyboard
x=60
while True:
try:
if keyboard.is_pressed('space'):
x=60
print(f"Timer reset to {x}")
elif keyboard.is_pressed('space'):
break
else:
print(f"{x} seconds left")
time.sleep(1)
x-=1
except Exception:
pass
This is my suggestion. The problem is, that time.sleep is blocking, so when it's sleeping you cannot break it by pressing escape. You will have to spam the escape button, but it works.
import keyboard
import time
t=60
last = False
current = False
while True:
current = keyboard.is_pressed('space') # triggered when space bar is pressed
if last == 0 and current == 1:
while t>=0:
if keyboard.is_pressed('escape'):
t = 60
last = False
current = False
print("Timer stopped.")
break
print(t)
t-=1
time.sleep(1)
last = current # reset
Sample output/test:
60
59
58
57
56
60
59
58
57
56
60
59
60
59
58
To suggest a solution without break:
import keyboard
import time
last = 0
current = 0
while True:
t=60
current = keyboard.is_pressed('space') # triggered when space bar is pressed
if last == 0 and current == 1:
current = 0
while t>=0 and current == 0:
print(t)
t-=1
time.sleep(1)
current = keyboard.is_pressed('space')
last = current # reset
Not sure how you want to manage long presses here. If the spacebar stays pressed for more than one second, the timer will reset several times in (technically) one keypress.

how to fix a random choice generator?

My python game isn't working, the sequences beginning with:
if int(total_time) > 10:
isn't triggering, but when I press D, C or W I am getting the 'you opened something' text though. The code there is right as far as I know, it's just not working. I used the or prevtime to allow you to do it the first time.
import random, time, pygame, sys
from pygame.locals import *
total_time = time.clock()
pygame.init()
XQR_prevtime = 0
ppayh_prevtime = 0
pu_ekaw_prevtime = 0
diff = 1
windowSurface = pygame.display.set_mode((400,400),0,32)
time.sleep(3)
XQR_awakened = False
ppayh_awakened = False
pu_ekaw_awakened = False
if int(total_time) > 10:
if int(XQR_prevtime) > (12 - diff) or int(XQR_prevtime) == 0 or XQR_awakened == True:
if XQR_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a mystery came in")
time.sleep(2)
sys.exit()
if random.randint(0,diff) == 1:
print(3)
XQR_prevtime = time.clock()
door_opening.play()
XQR_awakened = True
if int(ppayh_prevtime) > (12 - diff) or int(ppayh_prevtime) == 0 or ppayh_awakened == True:
if ppayh_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a friend came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
ppayh_prevtime = time.clock()
closet_opening.play()
ppayh_awakened = True
if int(pu_ekaw_prevtime) > (12 - diff) or int(pu_ekaw_prevtime) == 0 or pu_ekaw_prevtime == True:
if ekaw_up_awakened == True:
print("You left something open...")
time.sleep(2)
print("And an answer came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
pu_ekaw_prevtime = time.clock()
window_opening.play()
pu_ekaw_awakened = True
total_time never changes, so you can never reach your condition.
The line
total_time = time.clock()
assigns a numeric value (a float) to total_time. There is no reference back to the time.clock() function, the function returns just a normal float object, not a timer object.
And normal float values don't change, they are immutable. The total_time value is not going to change as you game runs.
If you want to measure elapsed time, just keep calling time.clock():
if time.clock() > 10:
You don't need to convert a float value to int here, comparisons with integers just work.

clock countdown calculation in python

I want to write a function called boom(h,m,s) that after input from main starts printing in HH:MM:SS format the countdown clock, and then prints "boom".
I'm not allowed to use existing modules except the time.sleep(), so I have to base on While\For loops.
import time
def boom(h,m,s):
while h>0:
while m>0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m-=1
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s=59
m=59
h-=1
while h==0:
while m==0:
while s>0:
print ("%d:%d:%d"%(h,m,s))
time.sleep(1)
s-=1
print ("BooM!!")
I figured how to calculate the seconds part, but when I input zeros on H and M parameters, it's messing with the clock.
The problem is here:
while h==0:
while m==0:
while s>0:
If m == 0, and s == 0 the while loop doesn't break, so there is an infinite loop.
Just add an else clause to the (last and) inner-most while, like so:
while s>0:
...
else: # executed once the above condition is False.
print ('BooM!!')
return # no need to break out of all the whiles!!
just convert it all to seconds and convert it back when you print ...
def hmsToSecs(h,m,s):
return h*3600 + m*60 + s
def secsToHms(secs):
hours = secs//3600
secs -= hours*3600
mins = secs//60
secs -= mins*60
return hours,mins,secs
def countdown(h,m,s):
seconds = hmsToSecs(h,m,s)
while seconds > 0:
print "%02d:%02d:%02d"%secsToHms(seconds)
seconds -= 1
sleep(1)
print "Done!"

Categories