Good evening,
I want keyboard input with visible timer (time to respond)
My code
import time
import sys
def initial_startup(t):
print('Do you want to continue?')
global input
input = input("Answer yes or no only:" + " ").lower()
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
if input == "yes" or input == "yup":
print("\n\nThanks script is now starting\n\n")
else:
pass
if input == "no" or input == "nope":
print("\nOk as you wish, I'm stopping...\n")
sys.exit(1)
if timer == "00:01":
print("Timeout! try again")
sys.exit(1)
t = 4
initial_startup(int(t))
I'm trying to get keyboard input with timeout and also want to show time below answer yes or no:
Prints timer after input ..
Want this output.
Output:
Do you want to continue?
Answer yes or no:
You have {timer} time left...
If input then continue else sys.exit which is already in code.
Thank you so much for helping to improve this newbie!
To do this you need to move with cursor in the terminal depending on the operating system you are using, it is very tiring and it is not very solid to use the terminal in that way (a static stdout would be easier and safer), what I would do it is an output of this kind obviously you have to use a multithread programming to be able to use the file descriptor simultaneously
import time
import sys
import threading
import time
import sys
def get_input(t):
global stop_threads
while True:
input_cmd = input().lower()
if input_cmd == "yes" or input_cmd == "yup":
print("\n\nThanks script is now starting\n\n")
break
elif input_cmd == "no" or input_cmd == "nope":
print("\nOk as you wish, I'm stopping...\n")
break
stop_threads = True
def initial_startup(t):
print('Do you want to continue?')
t1 = threading.Thread(target=get_input, args=(t,), daemon=True)
t1.start()
while t:
global stop_timeout
global stop_threads
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
prompt = "You have %s time left... Answer yes or no only: " % timer
print(prompt)
sys.stdout.write("\x1b[1A") # cursor up one line
sys.stdout.write("\x1b[2K") # delete the last line
if stop_threads:
sys.exit(1)
time.sleep(1)
t -= 1
if timer == "00:01":
sys.stdout.write("\x1b[2K") # delete the last line
print("Timeout! try again")
sys.exit(1)
stop_threads = False
stop_timeout = False
t = 4
initial_startup(int(t))
Output
Do you want to continue?
You have 00:02 time left... Answer yes or no only:
Ok as you wish, I'm stopping...
Do you want to continue?
You have 00:02 time left... Answer yes or no only:
Timeout! try again
Do you want to continue?
You have 00:05 time left... Answer yes or no only:
Thanks script is now starting
Related
I am trying to make an auto clicker but when i try to make my code exit it doesnt
here is my code
import mouse
import keyboard
import time
import os
os.system('cls')
def Config():
print("Click every")
hour = int(input("Hour: "))
minute = int(input("Minute: "))
second = int(input("Second: "))
total_time = hour*3600 + minute*60 + second
print("f6 to start and f10 to stop")
keyboard.wait('f6')
while True:
time.sleep(total_time)
mouse.click()
#def Fastest():
print(" Auto clicker!!!")
print(" By ze")
print("-------------------------")
print("Auto click on desired time or Fastest?")
choose = int(input("""
1. Config (No milliseconds)
2. Fastest
"""))
if choose == 1:
Config()
# elif choose == 2:
# Fastest()
#TODO:
# use mouse.click
# make it click with time
# make function fastest start with f1 and stops with f2
# create back up file
i tried an if statement with keyboard.is_pressed('key') thinking it would work but it doesnt my results are that the code exits (if key is pressed then exit)
You need to check if the key is pressed in your infinite loop. If it is pressed, you need to exit
while True:
time.sleep(total_time)
mouse.click()
if keyboard.is_pressed("f10"):
break
But this waits for the sleep function , so you'll need to hold f10 for total_time seconds.
You should use a loop to check for the key, rather than sleeping
import datetime
...
clicking = True
while clicking:
mouse.click()
s = datetime.datetime.now()
while ((datetime.datetime.now()-s).total_seconds() < total_time):
# This runs while the difference in time since you started the loop is less than the time you want to wait
if keyboard.is_pressed("f10"):
clicking = False
break
Use one thread to handle user input and another thread to do the clicking:
from threading import Thread
from msvcrt import getwch
import mouse
done = False
def auto_click():
print("Press \"q\" to quit")
global done
while True:
if getwch() == "q":
done = True
break
Thread( target = auto_click, daemon = True ).start()
while not done: # you can add whatever logic you want including a time gate here
mouse.click()
while 1:
wat=water()
if wat==10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first=input("Drank?Y/N")
if first.lower()=="y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
Is there any way to wait for a couple of minutes and if no input is provided, then take the value "n" as input for the first variable?
Guess by default it will wait indefinitely. I tried using a timer function, but it cannot record any input.
What I am trying to do is to track my activities, so if I drink water I say y--> this records my activity and writes it to a file.
All help will be greatly appreciated
Here is how you can use a combination of pyautogui.typewrite, threading.Thread and time.sleep:
from pyautogui import typewrite
from threading import Thread
from time import sleep
a = ''
def t():
sleep(5)
if not a: # If by 5 seconds a still equals to '', as in, the user haven't overwritten the original yet
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
a = input()
b = input() # Test it on b, nothing will happen
Here is the code implemented into your code:
from pyautogui import typewrite
from threading import Thread
from time import sleep
while 1:
wat = water()
if wat == 10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first = 'waiting...'
def t():
sleep(5)
if first == 'waiting...':
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
first = input("Drank?Y/N")
if first.lower() == "y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
I want to execute a function repeatedly every 5 seconds and at the same time take input from the user and based on the input stop the execution?
Ex:
def printit():
t=threading.Timer(3.0,printit)
t.start()
n=str(input())
if(n=='rajesh'):
t.cancel()
else:
#I want to continue the execution here
This Should Help
import time
#use a While loop
While True:
#request said user input
x= input("Please Press 1 to continue Or 2 to Exit")
#then an if statement
if x==1:
#call your function
printit()
time.sleep(5)
else:break
This should Do the trick
If you really want to use threading, then this should work:
import threading
import time
def worker():
while True:
user_input = input("Enter text:")
if user_input == 'rajesh':
break
else:
time.sleep(5)
thread = threading.Thread(target=worker, daemon=True)
thread.start()
thread.join()
This Should Help
#request said user input
x= input("Please Press 1 to continue Or 2 to Exit")
#use a While loop
While True:
#then an if statement
if x==1:
#call your function
printit()
else:break
This should Do the trick
import time
from threading import Timer
from random import randint
print("Every wrong answer is a 3s delay; you have 30s")
end = False
def lose():
print(end)
print("Time up!")
time.sleep(1)
print("Score is",pts,", with",wrong,"wrong answers.")
time.sleep(1)
input("enter to quit")
quit()
timer = Timer(10,lose)
timer.start()
pts = 0
wrong = 0
while end == False:
a = randint(5,50)
b = randint(5,50)
print(a,"+",b)
ans = input()
if ans.isnumeric():
ans = int(ans)
if ans == a+b:
print("correct")
pts = pts+1
else:
print("wrong,",a+b)
wrong = wrong+1
print("delay")
time.sleep(3)
print("delay end")
print("")
When the timer finishes, the loop overlaps the 'lose' function, and it messes up on the line like this:
Time up!
45 + 10
55
Score iscorrect
3
, with29 0+ wrong answers.37
enter to quitwrong,p
66
delay
How do I fix this issue?
Sorry if this question has already been answered, but I want to know.
Ideally, you should probably avoid using threads altogether, as mentioned in the comments.
However, if you are going to use threads, consider using a mutex to ensure that multiple threads are not trying to write to stdout at the same time.
For example:
# setup at the beginning:
from threading import Thread, Lock
mutex = Lock()
# surrounding each print statement:
mutex.acquire()
try:
print('text')
finally:
mutex.release()
I've made this little alarm clock with a little help from my brother. I tried it last night, with out the nonBlockingRawInput and that worked fine, but with the nonBlockingRawInput it didn't work. Today I've tried it but neither of them work! I will post the code with the nonBlockingRawInput and the "non" file. If you want the code without nonBlockingRawInput, just ask.
Thanks in advance.
alarm rpi.py:
import time
import os
from non import nonBlockingRawInput
name = input("Enter your name.")
print("Hello, " + name)
alarm_HH = input("Enter the hour you want to wake up at")
alarm_MM = input("Enter the minute you want to wake up at")
print("You want to wake up at " + alarm_HH + ":" + alarm_MM)
while True:
now = time.localtime()
if now.tm_hour == int(alarm_HH) and now.tm_min == int(alarm_MM):
print("ALARM NOW!")
os.popen("open mpg321 /home/pi/voltage.mp3")
break
else:
print("no alarm")
timeout = 60 - now.tm_sec
if nonBlockingRawInput('', timeout) == 'stop':
break
non.py:
import signal
class AlarmException(Exception):
pass
def alarmHandler(signum, frame):
raise AlarmException
def nonBlockingRawInput(prompt='', timeout=20):
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(timeout)
try:
text = input(prompt)
signal.alarm(0)
return text
except AlarmException:
pass
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return ''
I've been looking at your code for a while now. As far as I can understand you want to be able to run an alarm while also being able to type "stop" in the shell to end the program, to this end you can make the alarm a thread. The thread will check if its time to say "ALARM!" and open the mp3. If the user hasn't typed stop in the shell, the thread will sleep and check again later.
I essentially used your code and just put it into an alarm thread class:
import time
import os
import threading
class Alarm(threading.Thread):
def __init__(self, hours, minutes):
super(Alarm, self).__init__()
self.hours = int(hours)
self.minutes = int(minutes)
self.keep_running = True
def run(self):
try:
while self.keep_running:
now = time.localtime()
if (now.tm_hour == self.hours and now.tm_min == self.minutes):
print("ALARM NOW!")
os.popen("voltage.mp3")
return
time.sleep(60)
except:
return
def just_die(self):
self.keep_running = False
name = raw_input("Enter your name: ")
print("Hello, " + name)
alarm_HH = input("Enter the hour you want to wake up at: ")
alarm_MM = input("Enter the minute you want to wake up at: ")
print("You want to wake up at: {0:02}:{1:02}").format(alarm_HH, alarm_MM)
alarm = Alarm(alarm_HH, alarm_MM)
alarm.start()
try:
while True:
text = str(raw_input())
if text == "stop":
alarm.just_die()
break
except:
print("Yikes lets get out of here")
alarm.just_die()
It is worth noting, that when the thread is sleeping, with:
time.sleep(60)
And you typed stop in the shell the thread would have to wake up before it realised it was dead, so you could at worst end up waiting a minute for the program to close!
import winsound,time
a= int(input("Enter how many times I have beep :"))
b= int(input("Enter when to wake up (in seconds) :"))
time.sleep(b)
for i in range(a):
winsound.Beep(3000,100)
winsound.Beep(2500,100)
winsound.Beep(2000,100)
winsound.Beep(1000,100)
winsound.Beep(500,100)