簡體   English   中英

有沒有辦法保存倒數計時器的當前時間?

[英]Is there a way to save the current time of the countdown timer?

我想構建一個從 25 倒計時到 0 的程序。如果程序崩潰或用戶退出程序等,我想設法保存當前時間。

這是否可能做到這一點,我無法猜測程序何時結束。

所以我想將當前時間保存到一個文件中,然后從文件中讀取,然后從停止的地方啟動計時器。

from time import sleep

def countdown():
    time = 25
    while time > 0:
        print(time)
        sleep(1)
        time -= 1
        # if his program crashes, how can I save the current time ?

countdown()

我會將您的countdown()方法轉換為一個類,然后使用 pickle

# coding=utf-8
import os, pickle, time

SAVE_FILE = "saved_countdown.dat"

class Countdown(object):
    def __init__(self, t):
        """
        :param t: time to wait in seconds, float or int
        """
        self.t = t

    def run(self):
        while self.t > 1:
            time.sleep(1)
            self.t -= 1
            print("\rRemaining:", self.t, end="")
        time.sleep(self.t)
        self.t = 0
        print("\nCountdown finished.")


if __name__ == '__main__':
    try:
        if os.path.isfile(SAVE_FILE):
            with open(SAVE_FILE, "rb") as f:
                cd = pickle.load(f)
            print("Restored Countdown from file")
            os.remove(SAVE_FILE)
        else:
            cd = Countdown(25)
            print("No save file found, created new countdown")
        cd.run()
    except:
        if cd.t > 0:
            with open(SAVE_FILE, "wb") as f:
                pickle.dump(cd, f)
            print("Program crashed, saved backup file")

所有的印刷品都應該是非常自我解釋的

更多關於 try/except: https : //www.w3schools.com/python/python_try_except.asp

有關泡菜的更多信息: https : //www.datacamp.com/community/tutorials/pickle-python-tutorial

您可以使用文件來保存計時器時間,例如:

from time import sleep

def countdown(time=25):
    while time > 0:
        print(time)
        sleep(1)
        time -= 1
        # if his program crashes, how can I save the current time ?
        f = open("last_time.txt", "a")
        f.write(str(time))
        f.close()

# next time app opens you can read the file to know if there was a stopped timer
f = open("last_time.txt", "r")
if f.read():
    time = int(f.read()) 
    countdown(time)
else:
    countdown()

您可以在每次遞減計時器時寫出計時器的內容,然后在啟動時(如果文件存在)從文件中加載該值(如果存在)。

我在這里使用 JSON,因為它對於人類來說也是一種易於理解的格式(您也可以使用pickle模塊來序列化 python 數據)。 with語句確保文件在被讀取或寫入后正確關閉。

運行完文件后,我們通過取消鏈接(刪除)狀態文件來清理:

from time import sleep
import os
import os.path
import json

def countdown(persist_file=None):
    time = 25
    fp = None

    if persist_file and os.path.exists(persist_file):
        with open(persist_file, 'rb') as f:
            time = json.load(f)['previous_time']

    while time > 0:
        print(time)
        sleep(1)
        time -= 1
        # if his program crashes, how can I save the current time ?

        if persist_file:
            with open(persist_file, 'wb') as f:
                json.dump({'previous_time': time}, f)

    if persist_file:
        os.unlink(persist_file)

countdown(persist_file='test.persist')

您可以通過向字典中添加更多鍵及其包含的值來擴展被持久化的值集(或者通過將相關數據保存在您根據需要序列化和反序列化的字典中來持久化應用程序的狀態)。

這也可以優化以避免每次都重新打開文件,並通過序列化到臨時文件然后在舊狀態文件上重命名它而不是直接寫入狀態文件來提高對失敗的彈性。 然而,為了理解一般概念,這有望足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM