0

I am running a python script on a remote server through SSH. The script creates a new file, and writes some data to it. I do it in a while True block. When I kill the python process, my output file is empty. How to save data to the output file?

When I use CTRL+C file keeps all data. But I can't use this combination, because I run script on remote machine, and I can lose the connection. Also, I am confused for how long this script will be running if I stop my SSH connection.

with open('out/' + filename, 'a') as f:
    while True:
        r = get_updates()
        f.write(r.text)

        time.sleep(10)
ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52
Bogdan Popov
  • 113
  • 12

1 Answers1

1

write just queues output to be written. It's entirely up to the OS to decide when it actually writes to the file. If you want to make sure it actually reaches the file, you should also explicitly flush it:

with open('out/' + filename, 'a') as f:
    while True:
        r = get_updates()
        f.write(r.text)
        f.flush()

        time.sleep(10)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Worth to mention that Python will do that for you when it receives `Ctrl + C` (SIGTERM). Looks like the OP used `kill -9`. (Maybe he found that on the internet ;) ) – hek2mgl Dec 23 '18 at 18:03