在无限等待期间写入文件

2024-04-25 08:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要写在一个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地址


Tags: 文件代码importtxttruedatetimedateos
1条回答
网友
1楼 · 发布于 2024-04-25 08:52:53

将所有答案总结为一个:

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

相关问题 更多 >