0

I will preface this question with the fact that I know little about Python, but that's the language that the program I'm working with uses.

My job has a certain Python program that we use for debugging. It essentially listens to a network port and prints the sent debug information (as a string) to the screen. We have been having problems in the past, and being able to also log this to a file for future reference would be quite helpful.

Unfortunately, the program operates as an infinite loop, basically while True, if message received, print.

This was fine when it just printed back to the terminal, but if it's writing to a file, I need to close and flush it (I think) on exit, which is done with Ctrl+C. Currently, I don't have a f.close anywhere in there, since the program has no natural way to end. Instead, I set the third argument of open to False since I am told this makes it not buffer writes. But, do I still need to close the file, or is that done when Python exits? Long ago, I managed to lock a file "open" when I closed a Python program unexpectedly, and I'm not sure if this was a fluke.

Is there a way to stop the loop via user input (doesn't matter what) without actually waiting on user input as most methods of getting user input do? This would allow me to close the file and then exit normally, rather than have to use Ctrl+C.

I did investigate this answer, but the code is for Python 2.7 and runs on both Windows and Linux due, so it does not seem that any would apply. I have heard things about "raw_input" but do not know what it is or whether it is blocking.

RDragonrydr
  • 181
  • 9
  • 3
    You want to use `with open(...) as f:`, with everything that writes to the file in an indented block below that. If the block is exited by any means, the file automatically gets closed. – jasonharper Aug 02 '20 at 18:41
  • Including the ctrl+C keyboard interrupt? – RDragonrydr Aug 02 '20 at 19:34

0 Answers0