简体   繁体   English

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

[英]I'm writing a timer program that features the capability to start over, pause, or stop the timer

The problem that I am having is figuring out how to retrieve a time value from the broken timer() while loop and store it into the begintimer() function which would have a prompt section at the end of it which is the {/* implementation not shown */} segment. 我遇到的问题是弄清楚如何在循环时从损坏的timer()中检索时间值并将其存储到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()

A simple hack that you could do is to use at try to catch a KeyboardInterruption 您可以使用一个简单的技巧来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

The "Start?" 开始?” prompt in stopwatch() is in an infinite loop since keep_running's value isn't being changed when you call raw_input. stopwatch()中的提示处于无限循环中,因为调用raw_input时keep_running的值未更改。 Indenting the rest of the function will allow the rest of the code to run: 缩进该函数的其余部分将允许其余代码运行:

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

You also have an infinite loop in timer(). 您在timer()中也有一个无限循环。 The final yield call isn't enough to change the loop condition from True to False. 最终的yield调用不足以将循环条件从True更改为False。 There needs to be a condition in that loop that allows you to escape it. 该循环中需要有一个条件,可以让您对其进行转义。 You can also return the tuple instead of yielding it. 您也可以返回元组而不是屈服它。

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)

This is your code refactored to work. 这是您的代码重构工作。 Functions that use the keyword yield return generators. 使用关键字yield return生成器的函数。 The datetime module has classes suitable for this type of thing. datetime模块具有适用于此类事物的类。

Code: 码:

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()

In any case, there are modules written that already do this . 无论如何,已经编写了执行此操作的模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM