1

I need to write in a txt file during a infinite while. But it's not writing and if I don't use infinite while it's works. What do I have to change ? My goal is to ping different ip infinite time and when the ping fails, it's written in the file with the time and date

I've tried the code without the while True and it works. I think the code need to be stop to write but can we do without stop ?

import os
import datetime

fichier = open("log.txt", "a")
date = datetime.datetime.now()

hostnames = [
    '192.168.1.1',
    '192.168.1.2',
    '192.168.1.3',
]
while True :
    for hostname in hostnames:
        ping = os.system(" Ping " + str(hostname))
        if ping == 1:
            print("DOWN")
            fichier.write(str(date) + "    " + str(hostname) + '\n' + '\n')
        else:
            print("UP")

I expect the output when it's failed with a stamp Date/Time and the IP Address

Tim
  • 1,153
  • 11
  • 21
Micky
  • 33
  • 1
  • 1
  • 4

1 Answers1

1

To sum up all the answers in one:

try:
 with open('log.txt', 'a') as fichier:
   while True:
       for hostname in hostnames:
           ping = os.system(" Ping " + str(hostname))
           if ping == 1:
           print("DOWN")
           fichier.flush()
           fichier.write(str(date) + "    " + str(hostname) + '\n' + '\n')
       else:
           print("UP")
except KeyboardInterrupt:
     print("Done!")