我不知道这个代码怎么了?

2024-05-19 13:59:52 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
I'm new to python, I can't tell if this will work or not

import time
from sys import stdout
varthing = 1
while varthing == 1:
    time.sleep(1)
    checker = time.strftime("\r%b, %d %H:%M:%S", time.localtime())
    print checker,
    stdout.flush()
    if checker == "Dec, 25 00:00:00" :
        print "It's Christmas"
        raw_input("Enter anything to close\n")
        varthing = 0

我看没什么不对劲。它是一个闹钟,当圣诞节来临时通知你。你知道吗


Tags: toimportnewiftimestdoutcheckerthis
2条回答

如果你不需要每秒钟打印一次,这就可以了:

import datetime, time
target_date = datetime.datetime(2011, 12, 25)
time_left = target_date - datetime.datetime.now()
time.sleep(time_left.total_seconds())
print "It's Christmas"
  • strftime格式以\r开始。为什么?在if语句中测试的字符串将永远不会匹配,因为它不是以\r开头的。

  • time.sleep(1)不能保证只睡一秒钟。它可能睡眠时间更长,您将错过一秒钟的窗口,在该窗口中checker将匹配您正在测试的字符串。

相关问题 更多 >