我正在编写一个实现闹钟的python代码,我把一些YouTube链接放在文本文件中,程序将读取该文件。我必须以任何格式设置我想要的时间,在特定的时间,程序将从那些保存在文件中的随机链接中选择一个并开始播放。 但在if-else部分,我的程序陷入了无限循环。
有谁能帮我复习一下我犯错误的地方吗。
import random
import time
import webbrowser
from datetime import datetime
import subprocess
lines = open("C:\Python_code\Links.txt").read().splitlines()
mylines = random.choice(lines)
print(mylines)
time_input = str(raw_input("Please enter the time in HH:MM:SS format: "))
current_date = str(raw_input("Please enter the date in YYYY/MM/DD format: "))
selected_time = datetime.strptime('%s %s'%(current_date, time_input),"%Y/%m/%d %H:%M:%S")
print "Time selected: ",selected_time
while True:
if selected_time == time.localtime():
print "Alarm Now"
webbrowser.open(mylines)
break
else:
print "no alarm"
你可能想试试这个:
在你的时间比较中,你试图将苹果与桔子进行比较:
如果比较这两种不同的类型time.struct_time和datetime.datetime,即使这些对象中记录的时间相同,也会看到它为false。
如果将结构时间转换为日期时间,则比较将起作用:
我建议您使用time.sleep()函数,而不是循环并不断比较当前时间和闹钟时间。从你的报警时间中减去当前时间,然后再睡眠几秒钟。
相关问题 更多 >
编程相关推荐