1

我对编程完全陌生。想用 Python 写这个基本的闹钟,但是浏览器打不开。我认为这可能是我的 if 语句不起作用。那是对的吗?

from datetime import datetime
import webbrowser

name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")

now = datetime.today()

print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour,   now.minute, alarm_h, alarm_m))

if now.hour == alarm_h and now.minute == alarm_m:
    webbrowser.open(alarm_sound, new=2)   
4

2 回答 2

1

你可以试试这个简单的例子。

from datetime import datetime
import webbrowser
import threading


name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")
print alarm_sound
now = datetime.today()

def test():
    webbrowser.open(alarm_sound)

s1 = '%s:%s'
FMT = '%H:%M'
tdelta = datetime.strptime(s1% (alarm_h, alarm_m), FMT) - datetime.strptime(s1%(now.hour, now.minute), FMT)

l = str(tdelta).split(':')
ecar = int(l[0]) * 3600 + int(l[1]) * 60 + int(l[2])
print ecar

threading.Timer(ecar, test).start()

我们使用后threading打开一个。在您的示例中,您向用户询问小时和分钟,这样我们使用 just 计算两次之间的差异。webbrowsern secondshours and minutes

如果您需要更多解释,请发表评论。

于 2015-11-26T13:41:49.947 回答
0

您当前的代码看起来像是在根据设置的闹钟时间检查当前时间。但是,您目前只有一个检查,但您需要循环并不断将当前时间与设置的警报时间进行比较,或者使用另一种连续检查的方法。

网络浏览器行确实有效。它没有执行,因为当前时间从未达到闹钟时间(因为您没有不断地将当前时间与设置的闹钟时间进行比较)。

尝试:

from datetime import datetime
import webbrowser

name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")

now = datetime.today()

print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour, now.minute, alarm_h, alarm_m))

webbrowser.open(alarm_sound, new=2) #Added temporarily to test webbrowser functionality

if str(now.hour) == alarm_h and str(now.minute) == alarm_m: #Converted integer type to string type to match datatype of alarm_h and alarm_m
    webbrowser.open(alarm_sound, new=2)

这应该会打开网络浏览器,以便您可以测试其功能。

我还将now.hournow.minute转换为类型字符串以匹配alarm_halarm_m的数据类型。它们都是整数,不能直接与字符串数据类型进行比较。

绝对要研究循环或线程以不断更新当前时间并检查它是否等于当前线程。

于 2015-11-26T13:10:14.770 回答