首页 > 解决方案 > 在无限期间写入文件

问题描述

我需要在无限的时间内写入一个txt文件。但这不是写作,如果我在它工作时不使用无限。我必须改变什么?我的目标是 ping 不同的 ip 无限时间,当 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 地址

标签: pythonfilewhile-loopping

解决方案


将所有答案总结为一个:

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

推荐阅读