我在哥哥的帮助下制作了这个小闹钟。我昨晚尝试了nonBlockingRawInput
并且工作正常,但是nonBlockingRawInput
它没有用。今天我试过了,但它们都不起作用!我将使用nonBlockingRawInput
和"非"发布代码文件。如果您想要不带nonBlockingRawInput
的代码,请询问。
提前致谢。
闹钟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 ''
答案 0 :(得分:7)
我一直在看你的代码一段时间了。据我所知,您希望能够运行警报,同时还能够在shell中键入“stop”以结束程序,为此您可以将警报作为一个线程。线程将检查是否有时间说“ALARM!”并打开mp3。如果用户没有在shell中键入stop,则线程将休眠并稍后再次检查。
我基本上使用了你的代码并将其放入警报线程类:
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()
值得注意的是,当线程处于休眠状态时,使用:
time.sleep(60)
你在shell中键入了stop,线程必须先醒来才能意识到它已经死了,所以你可能最终会等待一分钟让程序关闭!
答案 1 :(得分:1)
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)