我正在编写一个计时器程序,它具有重新启动,暂停或停止计时器的功能

时间:2014-04-18 23:16:46

标签: python timer while-loop yield

我遇到的问题是如何在循环中从破碎的计时器()中检索时间值并将其存储到begintimer()函数中,该函数在其末尾有一个提示部分,即{ / *实现未显示* /}段。

import time
import sys


def timer(seconds, minutes, hours):
    time_start = time.time()
    seconds = 0
    minutes = 0
    hours = 0
    print("\n")
    print(time.time())
    print("seconds since the python epoch.\n")
    while True:
        sys.stdout.write("\r{hours}:{minutes}:{seconds}".format(hours=hours, minutes=minutes, seconds=seconds))
        time.sleep(1)
        seconds = int(time.time() - time_start) - minutes * 60
        if seconds >= 60:
            minutes += 1
            if minutes >= 60:
                hours += 1
                minutes = 0
            seconds = 0
        yield (seconds, minutes, hours)



def stopwatch():
    keep_running = 0
    while keep_running == 0:
        user_response = raw_input("Start?")
    if user_response in ["y", "yes", "Y", "YES", "Yes", "1", 1]:
            keep_running = begintimer(0,0,0)
    if user_response in ["n", "no", "N", "NO", "No", "0", 0]:
        keep_running = 2

def begintimer(sec, min, hou):
    sec = 0
    min = 0
    hou = 0
    sec, min, hou = timer(sec, min, hou)
    {/* implementation not shown */}

stopwatch()

3 个答案:

答案 0 :(得分:0)

你可以做的一个简单的黑客就是在try使用来抓住KeyboardInterruption

Time = 0
while True:
    try:
        t1 = time.time()
        **more code**
    except KeyboardInterruption: # use Ctrl + c to pause
        t2 = time.time()
        Time += t2 - t1
         ** query desire**
         if user_wants_to_continue:
            continue
         else:
            break

答案 1 :(得分:0)

“开始?” stopwatch()中的提示处于无限循环中,因为调用raw_input时不会更改keep_running的值。缩进函数的其余部分将允许其余代码运行:

def stopwatch():
    keep_running = 0
    while keep_running == 0:
        user_response = raw_input("Start?")
        if user_response in ["y", "yes", "Y", "YES", "Yes", "1", 1]:
            keep_running = begintimer(0,0,0)
        if user_response in ["n", "no", "N", "NO", "No", "0", 0]:
            keep_running = 2

你在timer()中也有一个无限循环。最终的yield调用不足以将循环条件从True更改为False。在该循环中需要有一个允许你逃避它的条件。你也可以返回元组而不是让它产生。

def timer(seconds, minutes, hours):
    time_start = time.time()
    seconds = 0
    minutes = 0
    hours = 0
    print("\n")
    print(time.time())
    print("seconds since the python epoch.\n")
    while True:
        sys.stdout.write("\r{hours}:{minutes}:{seconds}".format(hours=hours, minutes=minutes, seconds=seconds))
        time.sleep(1)
        seconds = int(time.time() - time_start) - minutes * 60
        if seconds >= 60:
            minutes += 1
            if minutes >= 60:
                hours += 1
                minutes = 0
            seconds = 0
        # escape condition
        if seconds >= 5:
            break
    return (seconds, minutes, hours)

答案 2 :(得分:0)

这是您重构的代码。使用关键字yield的函数返回生成器。 datetime模块具有适合此类事物的类。

代码:

import datetime
import time

def timer_gen(hours = 0, minutes = 0, seconds = 0):
    time_start = datetime.datetime.now()
    duration   = datetime.timedelta\
    (
        hours   = hours,
        minutes = minutes,
        seconds = seconds,
    )
    time_diff = datetime.datetime.now() - time_start
    while time_diff < duration:
        time_diff = datetime.datetime.now() - time_start
        hours  , remainder = divmod(int(time_diff.total_seconds()), 60*60)
        minutes, seconds   = divmod(remainder, 60)
        yield (hours, minutes, seconds)

def stopwatch():
    keep_running = 0
    while keep_running == 0:
        user_response = raw_input("Start?")
        if user_response in ["y", "yes", "Y", "YES", "Yes", "1", 1]:
                keep_running = begintimer(0, 0, 5)
        if user_response in ["n", "no", "N", "NO", "No", "0", 0]:
            keep_running = 2

def begintimer(hours = 0, minutes = 0, seconds = 0):
    timer = timer_gen(hours, minutes, seconds)

    for (hours, minutes, seconds) in timer:
        print('{} hrs {} mins {} secs'.format(hours, minutes, seconds))
        time.sleep(1)

stopwatch()

在任何情况下,都会编写已经执行this的模块。