我对编程完全不熟悉。想用Python编写这个基本的闹钟,但是webbrowser只是没有打开。我认为这可能是我的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)
答案 0 :(得分: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
在webbrowser
之后打开n seconds
。在你的例子中,你问用户的小时和分钟,这样我们只使用hours and minutes
计算两次之间的差异。
如果您需要更多解释,请发表评论。
答案 1 :(得分:0)
您当前的代码看起来正在根据设置的闹钟时间检查当前时间。但是,您目前只有一次检查,但您需要循环并连续比较当前时间和设定的闹钟时间,或使用其他连续检查方法。
webbrowser行确实有效。它没有执行,因为当前时间永远不会达到闹钟时间(因为你没有连续比较当前时间和设置的闹钟时间)。
尝试:
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)
这应该打开webbrowser,以便您可以测试其功能。
我还将 now.hour 和 now.minute 转换为类型字符串,以匹配 alarm_h 和 alarm_m 。它们都是整数,不能直接与字符串数据类型进行比较。
一定要查看循环或线程,以便不断更新当前时间并检查它是否等于当前线程。