0

我正在编写一个简单的命令行程序来显示当前时间并让用户设置闹钟。但是,警报没有响起,因为 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
4

3 回答 3

1

我发现使用全局变量和只有一个警报线程的实现有点奇怪。这样,您一次只能设置一个警报,即使没有设置任何警报,也总会有一个警报线程在运行。此外,您的 now 永远不会更新到警报根本不应该运行。也许考虑这样做。这只是一个快速重构,并不是说这是完美的,但它应该可以帮助您继续:

import datetime, time, threading, os


def clock():
    now = datetime.datetime.now()
    print now.strftime('%H:%M')

def set_alarm():    
    alarm_time = raw_input('Set Alarm (XX:XX) : ')    
    alarm_hour = alarm_time[:alarm_time.find(':')]
    alarm_minute = alarm_time[alarm_time.find(':')+1:]
    alarm_thread = threading.Thread(target=alert_thread, args=(alarm_time, alarm_hour, alarm_minute))
    alarm_thread.start()

def alert_thread(alarm_time, alarm_hour, alarm_minute):
    print "Ringing at {}:{}".format(alarm_hour, alarm_minute)
    while True:
        now = datetime.datetime.now()
        if str(now.hour) == str(alarm_hour) and str(now.minute) == str(alarm_minute):
            print ("Ring.. Ring..")
            break


#program start here
while True:
    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):
        break
于 2013-06-07T11:32:51.327 回答
0

raw_input()不会阻止其他线程打印。这是一个小例子:

from threading import Timer

def ring():
    print "\nRing.. Ring.."

t = Timer(3, ring) # ring in 3 seconds
t.start()
s = raw_input("wait for the ring, press enter afterwards")

输出:

wait for the ring, press enter afterwards..
Ring.. Ring..
于 2013-06-07T18:02:18.910 回答
0

2 件事

  1. 在线程的while循环中,放一个sleep
  2. 就在线程的内部 if 之前,执行

    现在 = datetime.datetime.now()

于 2013-06-07T11:56:43.033 回答