2 回答

TA贡献1856条经验 获得超17个赞
要在不覆盖现有内容的情况下继续向现有文件添加内容,您应该以“追加”模式打开。在您的代码中,您以“写入”模式打开。这将打开文件进行写入,但会覆盖现有内容。
具体来说,您的代码中的这一行:
with open(name, 'w') as outfile:
您应该将打开模式从 write ( 'w'
)更改为 append ( 'a'
)。
with open(name, 'a') as outfile:
如果这能解决您的问题,请告诉我。

TA贡献1891条经验 获得超3个赞
下面是代码的精简版:
import os
from multiprocessing import Pool
import json
import datetime
import time
hosts = ["192.168.1.47", "8.8.8.8"]
MAX_NUMBER_OF_STATUS_CHECKS = 2
FILE_NAME = 'hosts_stats.json'
#
# counter and sleep were added in order to simulate scheduler activity
#
def ping(host):
status = os.system('ping -o -c 3 {}'.format(host))
return datetime.datetime.now().strftime("%B %d %Y, %H:%M:%S"), {"monitor.ip": host,
"monitor.status": 'UP' if status == 0 else 'DOWN'}
if __name__ == "__main__":
p = Pool(processes=len(hosts))
counter = 0
if not os.path.exists(FILE_NAME):
with open(FILE_NAME, 'w') as f:
f.write('{}')
while counter < MAX_NUMBER_OF_STATUS_CHECKS:
result = p.map(ping, hosts)
with open(FILE_NAME, 'rb+') as f:
f.seek(-1, os.SEEK_END)
f.truncate()
for entry in result:
_entry = '"{}":{},\n'.format(entry[0], json.dumps(entry[1]))
f.writelines(_entry)
f.write('}')
counter += 1
time.sleep(2)
添加回答
举报