在停电前写入外部文件

Writing to an external file before a blackout

我在 raspberry pi 上有一个 python 计分板程序 运行ning,我需要它来在停电回来后恢复上面的信息(在我停电的地方很频繁)居住)。以下仅是保存机制的代码:

import pygame
from pygame.locals import *

if os.path.isfile('backup.txt'):
    print('Reloading details from previous game... ')
    backup = open('backup.txt', 'r')

    time_a = float(backup.readline().rstrip('\n'))
    team1name = backup.readline().rstrip('\n').upper()
    team2name = backup.readline().rstrip('\n').upper()
    team1score = int(backup.readline().rstrip('\n'))
    team2score = int(backup.readline().rstrip('\n'))
    currentperiod = int(backup.readline().rstrip('\n'))
    team1fouls = int(backup.readline().rstrip('\n'))
    team2fouls = int(backup.readline().rstrip('\n'))
    possesion = bool(backup.readline().rstrip('\n'))

pygame.time.set_timer(USEREVENT + 1, 100)

while True:  # Main loop
    clock.tick(30)
    for event in pygame.event.get():

        if event.type == USEREVENT + 1:  # Write to backup file
            backup = open('backup.txt', 'w')
            backup.write('{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(
                str(time_a), team1name, team2name, str(team1score), str(team2score),
                str(currentperiod), str(team1fouls), str(team2fouls), str(possesion)))
            pygame.time.set_timer(USEREVENT + 1, 100)

        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                backup.close()
                os.remove('backup.txt')
                sys.exit()

如果我通过kill -9 processID模拟停电,然后重新运行程序,没有错。但是如果我通过拔掉 pi 上的插头来模拟停电,backup.txt 是空的。

我试过更改保存频率 (USEREVENT+1)。

如何在实际停电前将程序保存到 backup.txt

直接写入磁盘而不是缓冲区解决了问题。做:

backup.flush()
os.fsync(backup.fileno())