非常基本的闹钟无法打开网络浏览器

Very basic alarm clock does not open webbrowser

我对编程完全陌生。想用 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)   

您当前的代码看起来像是在根据设置的闹钟时间检查当前时间。但是,您目前只有一次检查,您需要循环不断地将当前时间与设置的闹钟时间进行比较,或者使用其他方法不断检查。

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)

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

我也将 now.hournow.minute 转换为类型字符串以匹配 [=23 的数据类型=]alarm_h 和 alarm_m。它们都是整数,不能直接与字符串数据类型进行比较。

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

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

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()

我们用threadingn seconds后开一个webbrowser。在您的示例中,您要求用户提供小时和分钟,这样我们仅使用 hours and minutes 计算两次之间的差异。

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