python - 在无限 while 期间写入文件

标签 python file while-loop ping

我需要在无限时间内写入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 地址

最佳答案

将所有答案总结为一个:

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

关于python - 在无限 while 期间写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54111790/

相关文章:

python - 具有多个 groupby 的 pandas pivot 数据框

language-agnostic - 检查文件是否相同的最快方法是什么?

c++ - 文件或目录 _findfirst C++

java - 选择案例时如何跳出循环

java - 如何检查是否输入了四分之一的字符串?

java - 索引像素来为图片的某些位置着色

python - 从 Python 3.5 编译 Oracle 包时,不会填充 Oracle 12c DBA_IDENTIFIERS

python - 您可以将关键字参数而不是位置参数传递给 argparse 吗?

python - 城市/省/州列表与坐标?

linux - 通过 bash 在文件中搜索字符串,但只能匹配