English 中文(简体)
在停泊后维持最后功能似乎在沙捞中存在时间差异。
原标题:Running final function after stopping a loop seems to have a time difference in Python
  • 时间:2024-01-20 08:13:50
  •  标签:
  • python

我正在撰写一份“灰色”文字,其中将显示我在 t子上运行时掌握的数据,因为显示板被打破。 它将在Raspberry Pi上使用GPIO的皮条皮,这样,每当 t子的沥青环绕过面时,它就能够有一只金属片,短片(y子)。 计算速度取决于带的快速度。

This means time is very important here. I ve set up a loop in rev_counter() that gets the time and then when the "button" is pressed, it records the time again. Just to test it while I m writing this program, I ve simulated a button press with sleep(). I set it to 1.27841272276 seconds because this would be the time the belt would go around for a 7:30-minute mile pace. I ve been trying to get it as close to that pace as possible.

我不得不这样做。 在工作过程中显示胎儿时,它正确或可能是二分之一。 问题在于,在我结束工作时,采用了<代码>CTRL+C。 因此,平均微笑速度越快越快。 它应为7:30-7:31,但最终为7:34-7:36。 在我停止<代码>rev_counter ( loop)和在计算<代码>成果(之间,时间会相抵消。 出于某种原因,当我操作<代码>update_display()功能时,在rev_counter(<>/code> 和>上,似乎有所帮助。 能否在这个中间阻止造成问题? 为什么只有<条码>指示/代码>,而不是两个编号<>rev_counter()results()都得不到时间问题?

这里是我的圣迹:

import math
import os
import time
# from gpiozero import Button
from threading import Thread
from time import sleep

# belt_button = Button(2)


def display(original_time=None, total_distance=None, current_speed=None, prev_rev_time=None):
    os.system( clear )
    print( Current Workout Information )
    print(  )
    if original_time is None:
        print(f Time elapsed: --:--:-- )
        print(  )
        print( Distance )
        print(f Miles: -- )
        print(f Kilometers: -- )
        print(  )
        print( Current Speed )
        print(f M/H: -- )
        print(f KM/H: -- )
        print(  )
        print( Pace )
        print(f Mile: -- )
        print(f Kilometer: -- )
    else:
        seconds_elapsed = prev_rev_time - original_time
        time_elapsed = increment(seconds_elapsed)
        mi = total_distance / 5280
        km = total_distance / 3280.84
        mph = current_speed / 1.46667
        kmph = current_speed * 1.09728
        min_mi = 60 / mph
        min_km = 60 / kmph
        mi_pace_min = math.floor(min_mi)
        mi_pace_sec = round((min_mi * 60) % 60)
        if mi_pace_sec < 10:
            mi_pace_sec = f 0{mi_pace_sec} 
        km_pace_min = math.floor(min_km)
        km_pace_sec = round((min_km * 60) % 60)
        if km_pace_sec < 10:
            km_pace_sec = f 0{km_pace_sec} 
        print(f Time elapsed: {time_elapsed} )
        print(  )
        print( Distance )
        print(f Miles: {round(mi, 2)} )
        print(f Kilometers: {round(km, 2)} )
        print(  )
        print( Current Speed )
        print(f M/H: {round(mph, 2)} )
        print(f KM/H: {round(kmph, 2)} )
        print(  )
        print( Pace )
        if current_speed == 0:
            print(f Mile: 0 )
            print(f Kilometer: 0 )
        else:
            print(f Mile: {mi_pace_min}:{mi_pace_sec} )
            print(f Kilometer: {km_pace_min}:{km_pace_sec} )


def increment(seconds_elapsed):
    seconds_elapsed = math.floor(seconds_elapsed)
    h = seconds_elapsed // 3600
    m = (seconds_elapsed // 60) % 60
    s = seconds_elapsed % 60
    if h < 10:
        h = f 0{h} 
    if m < 10:
        m = f 0{m} 
    if s < 10:
        s = f 0{s} 
    return f {h}:{m}:{s} 


def rev_counter():
    revolutions = 0
    prev_rev_time = 0
    original_time = time.time()
    try:
        while True:
            prev_rev_time = time.time()
            # GPIO stuff
            # sleep(0.25)
            # belt_button.wait_for_press()
            sleep(1.27841272276)
            rev_time = time.time()
            revolutions += 1
            update_display(original_time, prev_rev_time, rev_time, revolutions)
            # Alternate code
            # thread = Thread(target=update_display, args=(original_time, prev_rev_time, rev_time, revolutions))
            # thread.start()
    except KeyboardInterrupt:
        os.system( clear )
        total_distance = 15 * revolutions
        results(original_time, prev_rev_time, total_distance)


def update_display(original_time, prev_rev_time, rev_time, revolutions):
    # feet * rev count
    # 15 = Length of my treadmill in feet
    total_distance = 15 * revolutions
    # feet / second
    rev_seconds = rev_time - prev_rev_time
    current_speed = 15 / rev_seconds
    display(original_time, total_distance, current_speed, prev_rev_time)


def results(original_time, prev_rev_time, total_distance):
    try:
        os.system( clear )
        seconds_elapsed = prev_rev_time - original_time
        time_elapsed = increment(seconds_elapsed)
        print( Workout Results )
        print(  )
        if total_distance == 0:
            print(f Total time: {time_elapsed} )
            print(  )
            print( Distance )
            print(f Miles: 0 )
            print(f Kilometers: 0 )
            print(  )
            print( Average Speed )
            print(f M/H: 0 )
            print(f KM/H: 0 )
            print(  )
            print( Average Pace )
            print(f Mile: 00:00 )
            print(f Kilometer: 00:00 )
        else:
            average_speed = total_distance / seconds_elapsed
            mi = total_distance / 5280
            km = total_distance / 3280.84
            mph = average_speed / 1.46667
            kmph = average_speed * 1.09728
            min_mi = 60 / mph
            min_km = 60 / kmph
            mi_pace_min = math.floor(min_mi)
            mi_pace_sec = round((min_mi * 60) % 60)
            if mi_pace_sec < 10:
                mi_pace_sec = f 0{mi_pace_sec} 
            km_pace_min = math.floor(min_km)
            km_pace_sec = round((min_km * 60) % 60)
            if km_pace_sec < 10:
                km_pace_sec = f 0{km_pace_sec} 
            print(f Total time: {time_elapsed} )
            print(  )
            print( Distance )
            print(f Miles: {round(mi, 2)} )
            print(f Kilometers: {round(km, 2)} )
            print(  )
            print( Average Speed )
            print(f M/H: {round(mph, 2)} )
            print(f KM/H: {round(kmph, 2)} )
            print(  )
            print( Average Pace )
            print(f Mile: {mi_pace_min}:{mi_pace_sec} )
            print(f Kilometer: {km_pace_min}:{km_pace_sec} )
        print(  )
        input( Exit  )
        os.system( clear )
    except KeyboardInterrupt:
        os.system( clear )


def main():
    os.system( clear )
    while True:
        try:
            print( AC Treadmill Workout Program )
            print(  )
            input( Start Workout  )
            display()
            rev_counter()
        except KeyboardInterrupt:
            print( 
 )
            print( Quitting...  )
            break


if __name__ ==  __main__ :
    main()

在没有任何问题的情况下实施这一方案,如果你改变所有<代码>os.system(明确) Line to os.system(cls )。 还确保把它放在终点站,因为我的电梯(PyCharm)确实允许它甚至在我确定原子辐射环境变数时加以清除。

最佳回答

我最后只使用<代码>Thread,然后才尽其所能。 后来,我会把该方案转换到C++,这样,它就能够取得更好的业绩,并且有全球倡议和各种障碍。

这里,它最后认为:

import math
import os
import time
from gpiozero import Button
from threading import Thread
from time import sleep

belt_button = Button(2)

# 15 is the length of my belt in feet
belt_length = 15


def display(original_time=None, total_distance=None, current_speed=None, prev_rev_time=None):
    os.system( clear )
    print( Current Workout Information )
    print(  )
    if original_time is None:
        print(f Time elapsed: --:--:-- )
        print(  )
        print( Distance )
        print(f Miles: -- )
        print(f Kilometers: -- )
        print(  )
        print( Current Speed )
        print(f M/H: -- )
        print(f KM/H: -- )
        print(  )
        print( Pace )
        print(f Mile: -- )
        print(f Kilometer: -- )
    else:
        seconds_elapsed = prev_rev_time - original_time
        time_elapsed = increment(seconds_elapsed)
        mi = total_distance / 5280
        km = total_distance / 3280.84
        mph = current_speed / 1.46667
        kmph = current_speed * 1.09728
        min_mi = 60 / mph
        min_km = 60 / kmph
        mi_pace_min = math.floor(min_mi)
        mi_pace_sec = round((min_mi * 60) % 60)
        if mi_pace_sec < 10:
            mi_pace_sec = f 0{mi_pace_sec} 
        km_pace_min = math.floor(min_km)
        km_pace_sec = round((min_km * 60) % 60)
        if km_pace_sec < 10:
            km_pace_sec = f 0{km_pace_sec} 
        print(f Time elapsed: {time_elapsed} )
        print(  )
        print( Distance )
        print(f Miles: {round(mi, 2)} )
        print(f Kilometers: {round(km, 2)} )
        print(  )
        print( Current Speed )
        print(f M/H: {round(mph, 2)} )
        print(f KM/H: {round(kmph, 2)} )
        print(  )
        print( Pace )
        if current_speed == 0:
            print(f Mile: 0 )
            print(f Kilometer: 0 )
        else:
            print(f Mile: {mi_pace_min}:{mi_pace_sec} )
            print(f Kilometer: {km_pace_min}:{km_pace_sec} )


def increment(seconds_elapsed):
    seconds_elapsed = math.floor(seconds_elapsed)
    h = seconds_elapsed // 3600
    m = (seconds_elapsed // 60) % 60
    s = seconds_elapsed % 60
    if h < 10:
        h = f 0{h} 
    if m < 10:
        m = f 0{m} 
    if s < 10:
        s = f 0{s} 
    return f {h}:{m}:{s} 


def rev_counter():
    revolutions = 0
    prev_rev_time = 0
    original_time = time.time()
    try:
        while True:
            prev_rev_time = time.time()
            sleep(0.25)
            belt_button.wait_for_press()
            rev_time = time.time()
            revolutions += 1
            thread = Thread(target=update_display, args=(original_time, prev_rev_time, rev_time, revolutions))
            thread.start()
    except KeyboardInterrupt:
        os.system( clear )
        total_distance = belt_length * revolutions
        results(original_time, prev_rev_time, total_distance)


def update_display(original_time, prev_rev_time, rev_time, revolutions):
    # feet * rev count
    # 15 = Length of my treadmill in feet
    total_distance = belt_length * revolutions
    rev_seconds = rev_time - prev_rev_time
    # feet / second
    current_speed = belt_length / rev_seconds
    display(original_time, total_distance, current_speed, prev_rev_time)


def results(original_time, prev_rev_time, total_distance):
    try:
        os.system( clear )
        seconds_elapsed = prev_rev_time - original_time
        time_elapsed = increment(seconds_elapsed)
        print( Workout Results )
        print(  )
        if total_distance == 0:
            print(f Total time: {time_elapsed} )
            print(  )
            print( Distance )
            print(f Miles: 0 )
            print(f Kilometers: 0 )
            print(  )
            print( Average Speed )
            print(f M/H: 0 )
            print(f KM/H: 0 )
            print(  )
            print( Average Pace )
            print(f Mile: 00:00 )
            print(f Kilometer: 00:00 )
        else:
            average_speed = total_distance / seconds_elapsed
            mi = total_distance / 5280
            km = total_distance / 3280.84
            mph = average_speed / 1.46667
            kmph = average_speed * 1.09728
            min_mi = 60 / mph
            min_km = 60 / kmph
            mi_pace_min = math.floor(min_mi)
            mi_pace_sec = round((min_mi * 60) % 60)
            if mi_pace_sec < 10:
                mi_pace_sec = f 0{mi_pace_sec} 
            km_pace_min = math.floor(min_km)
            km_pace_sec = round((min_km * 60) % 60)
            if km_pace_sec < 10:
                km_pace_sec = f 0{km_pace_sec} 
            print(f Total time: {time_elapsed} )
            print(  )
            print( Distance )
            print(f Miles: {round(mi, 2)} )
            print(f Kilometers: {round(km, 2)} )
            print(  )
            print( Average Speed )
            print(f M/H: {round(mph, 2)} )
            print(f KM/H: {round(kmph, 2)} )
            print(  )
            print( Average Pace )
            print(f Mile: {mi_pace_min}:{mi_pace_sec} )
            print(f Kilometer: {km_pace_min}:{km_pace_sec} )
        print(  )
        input( Exit  )
        os.system( clear )
    except KeyboardInterrupt:
        os.system( clear )


def main():
    os.system( clear )
    while True:
        try:
            print( ASHER Treadmill Workout Program )
            print(  )
            input( Start Workout  )
            display()
            rev_counter()
        except KeyboardInterrupt:
            print( 
 )
            print( Quitting...  )
            break


if __name__ ==  __main__ :
    main()

问题回答

The issue you re experiencing might be related to the fact that when you interrupt the rev_counter() loop with a keyboard interrupt , the KeyboardInterrupt exception is caught, and the results() function is called. However, the update_display() function is not called in the interrupt scenario. To address this, you can modify your code to ensure that update_display() is called before the results() function when a keyboard interrupt occurs. Here s a modified

def rev_counter():
    revolutions = 0
    prev_rev_time = 0
    original_time = time.time()
    try:
        while True:
            prev_rev_time = time.time()
            # GPIO stuff
            # sleep(0.25)
            # belt_button.wait_for_press()
            sleep(1.27841272276)
            rev_time = time.time()
            revolutions += 1
            update_display(original_time, prev_rev_time, rev_time, revolutions)
            # Alternate code
            # thread = Thread(target=update_display, args=(original_time, prev_rev_time, rev_time, revolutions))
            # thread.start()
    except KeyboardInterrupt:
        os.system( clear )
        total_distance = 15 * revolutions
        update_display(original_time, prev_rev_time, rev_time, revolutions)
        results(original_time, prev_rev_time, total_distance)




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签