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 地址
解决方案
将所有答案总结为一个:
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!")
推荐阅读
- firebase - Firebase 非致命问题不会导出到 BigQuery
- python - C# Unity - 统一从相机中提取像素数组并在 python 中显示
- google-maps - Google Maps Static API - 推荐人政策问题
- python - 根据其中一个的列和另一个的行连接两个数据框
- python - 通过 Pandas 从数据库请求表数据时如何获取正确的块?
- powershell - Powershell - Active Directory - 将用户移动到基于 CSV 文件的员工 ID 和日期的 OU
- python - pandas:根据一列中的相似值,使用来自多个数据帧的值填充数据帧中的空列
- php - 无法使用 cassandra 和 php 创建键空间
- python - 如何对特定列中的值进行分组和计数
- ios - 无法使用混合 Cordova 离子 iOS 应用的 Appium 检查来识别元素