0

我之前也问过类似的问题,但这次有点不同。对我来说,下面的代码应该可以工作。

import datetime
# run infinitly
while(True):

  done = False

  while(not done):
    #
    #main program
    #


    #stopping condition
      if currenttime == '103000':
        done = True

  #continue with rest of program

但是,当它到达上午 10:30:00 时,它不会继续程序的其余部分。

我知道的以下程序有效(在树莓派上):

import datetime
done = False
while not done:
    currenttime = datetime.datetime.now().strftime('%H%M%S')
    if currenttime != '103000':
        print currenttime
    if currenttime == '103000':
        done = True
print 'It is 10:30:00am, the program is done.'

我在第一个例子中所做的事情对我来说是合乎逻辑的。有谁知道为什么它不会退出该循环并继续其余部分?

4

4 回答 4

3

如果主程序运行时间较长,currenttime可以从 跳转102958103005。因此完全跳过103000

于 2013-06-28T16:24:02.547 回答
1

也许您需要在检查之前设置当前时间?此外,该if语句必须恰好在 103000 处done = True执行才能执行。

while(True):

  done = False

  while(not done):
    #
    #main program
    #

    # need to set current time
    currenttime = datetime.datetime.now().strftime('%H%M%S')

    #stopping condition (use >= instead of just ==)
      if currenttime >= '103000':
        done = True

  #continue with rest of program
于 2013-06-28T16:23:31.243 回答
1

请注意,不能保证您的循环在每一可用秒内都有一次迭代。系统上的负载越多,循环跳过一秒钟的可能性就越大,这可能是终止标准。也有可能跳过秒的情况,例如由于时间同步或夏令时问题。

您可以以秒为单位预先计算 timedelta,然后再休眠这么多秒,而不是忙于等待循环。

优点:

  • 您将节省计算机上其他进程可以使用的计算能力。
  • 它可能会增加硬件的使用寿命。
  • 这也将更加节能。

例子:

import datetime
import time
def wait_until_datetime(target_datetime):
    td = target_datetime - datetime.datetime.now()
    seconds_to_sleep = td.total_seconds()
    if seconds_to_sleep > 0:
        time.sleep(seconds_to_sleep)

target_datetime = datetime.datetime(2025, 1, 1)
wait_until_datetime(target_datetime)
print "Happy New Year 2025!"

请注意,由于系统日期和时间设置的任意更改,这可能仍然无法产生所需的行为。可能最好采用完全不同的策略在特定时间执行特定命令。您是否考虑过使用 cron 作业来实现所需的行为?(您可以向进程发送一个信号,从而发出它来取消循环......)

于 2013-06-28T17:11:48.757 回答
0
import datetime
done = False
while True:
    currenttime = datetime.datetime.now().strftime('%H%M%S')
    if currenttime >= '103000':
        break
    print currenttime
print 'It is 10:30:00am, the program is done.'

如果您不能使用中断:

import datetime
done = False
while not done:
    currenttime = datetime.datetime.now().strftime('%H%M%S')
    if currenttime >= '103000':
        done = True
    else:
        print currenttime
print 'It is 10:30:00am, the program is done.'
于 2013-06-28T18:19:44.937 回答