我有一个在树莓派上运行的python记分板程序,从停电(我经常居住的地方)回来后,我需要它来恢复有关它的信息。以下是仅用于保存机制的代码:
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
?
答案 0 :(得分:0)
直接写入磁盘而不是写入缓冲区可以解决此问题。做:
backup.flush()
os.fsync(backup.fileno())