Python Alarm Clock - python

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)

Related

Keyboard input timeout with visible countdown

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

How to countdown for timer user to input something [duplicate]

This question already has answers here:
Keyboard input with timeout?
(28 answers)
Closed 3 years ago.
What I would like to be able to do is ask a user a question using input. For example:
print('some scenario')
prompt = input("You have 10 seconds to choose the correct answer...\n")
and then if the time elapses print something like
print('Sorry, times up.')
Any help pointing me in the right direction would be greatly appreciated.
If it is acceptable to block the main thread when user haven't provided an answer:
from threading import Timer
timeout = 10
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
prompt = "You have %d seconds to choose the correct answer...\n" % timeout
answer = input(prompt)
t.cancel()
Otherwise, you could use #Alex Martelli's answer (modified for Python 3) on Windows (not tested):
import msvcrt
import time
class TimeoutExpired(Exception):
pass
def input_with_timeout(prompt, timeout, timer=time.monotonic):
sys.stdout.write(prompt)
sys.stdout.flush()
endtime = timer() + timeout
result = []
while timer() < endtime:
if msvcrt.kbhit():
result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
if result[-1] == '\r':
return ''.join(result[:-1])
time.sleep(0.04) # just to yield to other processes/threads
raise TimeoutExpired
Usage:
try:
answer = input_with_timeout(prompt, 10)
except TimeoutExpired:
print('Sorry, times up')
else:
print('Got %r' % answer)
On Unix you could try:
import select
import sys
def input_with_timeout(prompt, timeout):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [],[], timeout)
if ready:
return sys.stdin.readline().rstrip('\n') # expect stdin to be line-buffered
raise TimeoutExpired
Or:
import signal
def alarm_handler(signum, frame):
raise TimeoutExpired
def input_with_timeout(prompt, timeout):
# set signal handler
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout) # produce SIGALRM in `timeout` seconds
try:
return input(prompt)
finally:
signal.alarm(0) # cancel alarm
Interesting problem, this seems to work:
import time
from threading import Thread
answer = None
def check():
time.sleep(2)
if answer != None:
return
print("Too Slow")
Thread(target = check).start()
answer = input("Input something: ")

Is there anyway to wait for a couple of minutes and if no input is provided then take the value "n" as input for first variable?

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

How to ask Question by if statement via timeout

is there any way for ask question by if statement and after afew sec if user didnot give any answer , if state use a default answer?
inp = input("change music(1) or close the app(2)")
if inp = '1':
print("Music changed)
elif inp = '2':
print("good by")
in this case if user dont give any answer after 30 sec by default if statement choose number 3
from threading import Timer
out_of_time = False
def time_ran_out():
print ('You didn\'t answer in time') # Default answer
out_of_time = True
seconds = 5 # waiting time in seconds
t = Timer(seconds,time_ran_out)
t.start()
inp = input("change music(1) or close the app(2):\n")
if inp != None and not out_of_time:
if inp == '1':
print("Music changed")
elif inp == '2':
print("good by")
else:
print ("Wrong input")
t.cancel()
Timer Objects
This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a
subclass of Thread and as such also functions as an example of
creating custom threads.
Timers are started, as with threads, by calling their start() method.
The timer can be stopped (before its action has begun) by calling the
cancel() method. The interval the timer will wait before executing its
action may not be exactly the same as the interval specified by the
user.
For example:
def hello():
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
class threading.Timer(interval, function, args=None, kwargs=None)
Create a timer that will run function with arguments args and keyword
arguments kwargs, after interval seconds have passed. If args is None
(the default) then an empty list will be used. If kwargs is None (the
default) then an empty dict will be used.
cancel()
Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting
stage.
Here's an alternative way to do it (python 3), using multiprocessing. Note, to get the stdin to work in the child process, you have to re open it first. I'm also converting the input from string to int to use with the multiprocessing value, so you might want to error check there as well.
import multiprocessing as mp
import time
import sys
import os
TIMEOUT = 10
DEFAULT = 3
def get_input(resp: mp.Value, fn):
sys.stdin = os.fdopen(fn)
v = input('change music(1) or close the app (2)')
try:
resp.value = int(v)
except ValueError:
pass # bad input, maybe print error message, try again in loop.
# could also use another mp.Value to signal main to restart the timer
if __name__ == '__main__':
now = time.time()
end = now + TIMEOUT
inp = 0
resp = mp.Value('i', 0)
fn = sys.stdin.fileno()
p = mp.Process(name='Get Input', target=get_input, args=(resp, fn))
p.start()
while True:
t = end - time.time()
print('Checking for timeout: Time = {:.2f}, Resp = {}'.format(t, resp.value))
if t <= 0:
print('Timeout occurred')
p.terminate()
inp = DEFAULT
break
elif resp.value > 0:
print('Response received:', resp.value)
inp = resp.value
break
else:
time.sleep(1)
print()
if inp == 1:
print('Music Changed')
elif inp == 2:
print('Good Bye')
else:
print('Other value:', inp)

Python 3 I can't get my alarm to play

So I have a code I'm working on to automatically play my alarms at the times I specify. It also is playing some city sounds to help me sleep and while playing those sounds I can't get the while loop to end to have the alarm sound to play.
I tried to bring the while loop into the alarm function I've created but that didn't work but I'm fairly certain it has something to do with my while loops. But I'm thinking a fresh pair of eyes might do this code some good.
'''
Title: This is an alarm that perfectly lines up with my sleep schedule
Author: Riley Carpenter
'''
from pygame import mixer
import time
import os
import sys
import random
snoozeorstop = " "
Currenttime = time.ctime()
Hours1 = int(Currenttime[11:13])
Minutes1 = int(Currenttime[14:16])
Seconds = int(Currenttime[17:19])
optionalsongs = ["Pink Floyd Time.wav","Alarm2.wav","Alarm3.wav","Alarm4.wav","Alarm5.wav","Alarm6.wav","Alarm7.wav","Alarm8.wav","Alarm9.wav","Alarm10.wav","Alarm11.wav"]
phrases = ["Wake up Riley!!!!","It's time to wake up it's time to wake up","HEEEEYYY WAKE UP","RILEY RILEY RILEY WAKE UP","1 2 3 4 5 6 7 8 9 it is time to wake up","Riley more alarms are to come UNLESS you get up","OH WHEN SHALL I SEE JESUS you wanna not hear this again? Wake up","I'm so tired of telling you to wake up just wake up","A friend of the devil is somehow who doesn't wake up","Babe babe bae wake up"]
def playsound(soundfile):
mixer.init()
mixer.music.load(soundfile)
mixer.music.play(-1)
def stopsound():
mixer.music.stop()
def alarm(hour,minute):
print("")
print("")
print(random.choice(phrases))
if Hours1 == hour and Minutes1 == minute:
stopsound()
playsound(random.choice(optionalsongs))
print("")
snoozeorstop = input("Do you want to stop the song? ")
if snoozeorstop == "stop":
stopsound()
citysounds = input("Do you want to play the soothing sounds of the city? ")
if citysounds == "y" or citysounds == "Yes" or citysounds == "Y" or citysounds == "yes":
playsound("Citys Night ambience sounds.wav")
else:
playsound("Beginningsound.wav")
amount = 0
print("This is how many second has passed since this alarm was turned on")
while Hours1 != 5 and Minutes1 != 0:
Currenttime = time.ctime()
print(amount)
Hours1 = int(Currenttime[11:13])
Minutes1 = int(Currenttime[14:16])
Seconds = int(Currenttime[17:19])
amount += 1
time.sleep(1)
alarm(5,00)
alarm(5,5)
alarm(5,10)
alarm(5,15)
alarm(5,20)
alarm(5,25)
alarm(5,30)
alarm(5,35)
alarm(5,40)
alarm(5,45)
alarm(5,50)
alarm(5,55)
alarm(6,00)
alarm(6,5)
alarm(6,10)
alarm(6,15)
alarm(6,20)
alarm(6,25)
Since the while loop is central to your program, why not write that piece of code first. When that works as intended you can add songlists etc.
As for checking for the time when the alarm should go off you might want to check out the datetime module which makes time calculations much easier. For example:
import datetime, time
start = datetime.datetime.now()
alarm = start + datetime.timedelta(seconds=5) # Set alarm time 5 seconds from now
while True:
now = datetime.datetime.now() # When is this?
print(now.strftime("%H:%M:%S")) # Print human readable time
if now > alarm: # Have I passed the alarm time?
print('Alarm') # Sound the alarm
break # Leave this loop
time.sleep(1)

Categories