命令行多线程

时间:2013-06-07 10:51:31

标签: python multithreading python-multithreading raw-input

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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

2件事

  1. 在线程的while循环中,进行一次睡眠
  2. 在线程的内部if之前,执行

    now = datetime.datetime.now()

答案 2 :(得分: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..