我正在编写一个简单的命令行程序来显示当前时间并让用户设置闹钟。但是,警报没有响起,因为 raw_input 阻止了它。我什至实现了多线程,但效果不佳。这是完整的代码:
import datetime, time, thread, os
program_running = True
now = datetime.datetime.now()
alarm_status = 0
alarm_hour = 0
alarm_minute = 0
def clock():
now = datetime.datetime.now()
print now.strftime('%H:%M')
def set_alarm():
global alarm_hour, alarm_minute, alarm_status
alarm_time = raw_input('Set Alarm (XX:XX) : ')
alarm_hour = alarm_time[:alarm_time.find(':')]
alarm_minute = alarm_time[alarm_time.find(':')+1:]
alarm_status = 1
def alert_thread():
global alarm_hour, alarm_minute, alarm_status
while True:
if(alarm_status):
if (str(now.hour) == str(alarm_hour) and str(now.minute) == str(alarm_minute)):
print 'Ring.. Ring..'
alarm_status = 0
#program start here
thread.start_new_thread(alert_thread,())
while(program_running):
now = datetime.datetime.now()
print '1) Clock'
print '2) Alarm'
print '3) Quit'
choice = input('Choose (1-6) : ')
if(choice==1):
clock()
elif(choice==2):
set_alarm()
elif(choice==3):
program_running = False