当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Why is my print function delayed?

问题描述:

I'm really struggling to understand why it's not working the way I think it should.

Edit: Sorry for any confusion, it is the first print that will not execute. print('The alarm will sound at ' + result, flush=True)

Nothing happens until if time.strftime('%H:%M') == result is True. No matter where I put the print function, it will not run until the above is met. Even inside the while loop, it will not run.

#! /usr/bin/python

import argparse

import time

import datetime

def alarm(set_time):

set_time = str(set_time)[:2]+ ':' + str(set_time)[2:]

alarm_time = datetime.datetime.strptime(set_time,'%H:%M').strftime('%H:%M')

return alarm_time

def main():

parser = argparse.ArgumentParser()

parser.add_argument('wake', help='The time for the alarm to sound', type=str)

args = parser.parse_args()

result = alarm(args.wake)

print('The alarm will sound at ' + result, flush=True)

while True:

if time.strftime('%H:%M') == result:

print('Wake up')

return

else:

time.sleep(1)

pass

if __name__ == '__main__':

main()

网友答案:

I suggest you the change below. It's work fine.

import argparse
import time
import datetime

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('wake', help='The time for the alarm to sound', type=str)
    args = parser.parse_args()


    time_part = args.wake.split(':')

    d = datetime.datetime.now()

    wake_time = datetime.datetime(d.year, d.month, d.day, int(time_part[0]), int(time_part[1]), 0, 0)


    print('The alarm will sound at ' + args.wake, flush=True)

    while True:

        if datetime.datetime.now() > wake_time:
            print('Wake up')
            return
        else:
            time.sleep(1)
            pass

if __name__ == '__main__':
    main()
分享给朋友:
您可能感兴趣的文章:
随机阅读: