2

I have a rc522 RFID card Reader connected to my Raspberry pi 3. I have written a Python program that writes the cardnumber of the logged card to a file. That is working nice. I have also made a "systemd service" that starts this Python program on system startup. That's working fine too. It writes the cardnumbers to the file. But only after the system shuts down normally. When the system shutdown unexpectedly the card numbers are not written to the file. I can log cards the whole day but when the system shuts down unexpected all card numbers I have logged are gone. This happens only when the program is started by the "systemd service". When I start the program myself it writes all to the file immediately. That's also the case when the system shuts doen unexpected. All cardnumbers has then been written to the file. I assume that when the program is started by the systemd service the logged cardnumbers stay in memory until the system shuts down normally. Is there a way I can force the writing to file when it's started by the systemd service and not kept in memory? I have also tried it with a crontab job but that has the same problem. The code for writing to file is:

with open(path and filename, "a") as file:
    file.write(cardnumber)
Barmar
  • 741,623
  • 53
  • 500
  • 612
JoostR
  • 21
  • 1
  • 1
    You can add a flush call to save state. – stark Mar 28 '22 at 13:57
  • `with` automatically closes the file, which flushes it. @stark – Barmar Mar 28 '22 at 14:39
  • I didn't know about flush so I looked it up an in my python code I did put the next line directly under the with open(): "sys.stdout.flush()". But that does not help. I also tried "file.flush()" No result either. – JoostR Mar 28 '22 at 15:03
  • In my systemd service file I already started the python program with the parameter "-u" (=unbuffered). Like this: "ExecStart=/usr/bin/python3 -u program.py &". But that was not helping either. – JoostR Mar 28 '22 at 15:13

1 Answers1

0

The answer to my problem was as @stark stated. I had indeed to flush() the file. But I also had to add after that commmand the command "os.fsync()". And that last command is essential. Otherwise the flush won't activated. That answer I found in this question on Stackoverflow: how often does python flush to file Now when I add a cardnumber and immediatly after that the system unexpectacly powers down that cardnumber was written to file. My code looks now like this:

with open('path and filename', 'a') as file:
   file.write('text\n')
   file.flush()
   os.fsync(file)
JoostR
  • 21
  • 1