Gracefully Exit A Program

I have a program I'm using to read data from a serial port and write it to a CSV file. One day it just stopped writing correctly, and it appears to be related to how the program terminates when you click the stop button. Now the CSV file is just empty unless I put a finite loop on the read from serial / write to csv section (this used to not be the case).

I have tried doing a keyboard handler for Ctrl-C so the system would gracefully exit. Using an atexit routine. And about 30 other things so far. But I am just getting nowhere. How does PyCharm terminate programs, and is there any way to send a signal which I can process instead of just doing force termination?


The basic code I have is as follows:


with open('csvfile.csv','w') as csvfile:
      writer = csv.write(csvfile,dialect='excel', deliminator=',', lineterminator='\n')
      writer.writeRow(['Row header stuff'])

      while True:
          serRet = ser.readline()
          print(str(serRet))
          writetoCSV(str(serRet), writer)

This used to work fine. Suddenly one day it just stopped working. And now I have to add:

Count = 0

      while count < NUM:
          serRet = ser.readline()
          print(str(serRet))
          writetoCSV(str(serRet), writer)
          count = count + 1

Which does result in an exit code of 0, and the file being written correctly. But does not accomplish what I'm trying to accomplish. (there is no reason to know in advance what NUM will be)

Any help would be greatly appreciated!
1 comment
Comment actions Permalink
I will return a count or status code or somesuch. It's up to you to decide whether to check that and whether any particular status code means it's safe to call some other method. I prefer not to rely on the client to remember to check status codes.
0

Please sign in to leave a comment.