无限期间写入文件

时间:2019-01-09 13:56:24

标签: python file while-loop ping

我需要在无限时间内写入txt文件。但这不是写作,如果我在作品中不使用无限的话。 我必须改变什么? 我的目标是对不同的ip无限时间执行ping操作,当ping操作失败时,它将与时间和日期一起写入文件中。

我尝试了不使用while True的代码,并且可以正常工作。 我认为代码需要停止编写,但是我们可以不停地做吗?

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")

我期望输出带有时间戳记日期/时间和IP地址的输出失败

1 个答案:

答案 0 :(得分:1)

总结所有答案:

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!")