将Python词典保存到文件,并定期更新 [英] Save Python dictionary to file, and update it periodically

查看:44
本文介绍了将Python词典保存到文件,并定期更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这是一个非常简单的问题,这里有很多非常相似的问题,但是我仍然不知道如何获得想要的东西.我正在使用可以在联机时连接到的远程设备.我想要一个记录设备最新运行时间的文件,如下所示:

I feel like this is a very simple problem and there are a lot of very similar questions to it here, but I still can't figure out how to get what I want. I am working with remote devices that I can connect to when they are online. I want to have a file that records the most recent uptime of a device, like this:

# device ID ......... last seen online
{'deviceID1':'Wed Nov 08 2017 06:11:27 PM',
'deviceID2':'Wed Nov 08 2017 06:11:27 PM',
'deviceID3':'Tues Nov 07 2017 03:47:01 PM'}

等通过将其存储在json文件中并进行json.dumps存储数据并通过json.load进行查看,我已经非常接近了.我的代码遵循以下步骤:"ping所有设备ID",检查输出"和将结果写入文件".但是,每次执行此操作时,在线和现在不在线的设备的值都会被覆盖.像这样,而不是上面,我得到的像是:

etc. I've gotten really close by storing this in a json file and doing json.dumps to store the data and json.load to view it. My code follows the steps: 'ping all device IDs', 'check output', and 'write result to file'. But every time I do this, the values get overwritten for devices that were online and are now not online. As in, instead of the above, I get something like:

# device ID ......... last seen online
{'deviceID1':'Wed Nov 08 2017 06:11:27 PM',
'deviceID2':'Wed Nov 08 2017 06:11:27 PM',
'deviceID3':''}

当我在2017年11月8日星期三检查时,deviceID3不在线.但是我想保留该值,同时更新我在网上看到的设备的值.从本质上讲,我怎样才能将这个字典/数据保存在一个文件中,并每次针对同一组唯一的设备ID进行更新?这个问题最接近,但这就是附加条目,我想更新已经存在的键的值.谢谢.

when I check at Wed Nov 08 2017 06:11:27 PM and deviceID3 is not online. But I want to preserve that value while updating the values of the devices I do see online. How can I essentially keep this dictionary / data in a file and update it for the same set of unique device IDs every time? This question gets the closest, but that's about appending entries, and I want to update the values of keys that are already there. Thanks.

相关代码:

def write_to_file(data):
    with open(STATUS_FILE, 'w') as file:
        file.write(json.dumps(data))

def create_device_dictionary(deviceIDs):
    devices = {}
    for i in range(0, len(deviceIDs)):
        devices[deviceIDs[i]] = []
    return devices

def check_ping_output(cmd_output_lines,devices):

    for i, line in enumerate(cmd_output_lines):
        device_id = line.strip().strip(':')
        # if the device pinged back...
        if 'did not return' not in cmd_output_lines[i+1]:
            #current UNIX time
            human_readable_time = time.strftime(
                '%a %b %d %Y %I:%M:%S %p',
                time.gmtime(time.time())
            )
            devices[device_id].append(human_readable_time)
        else:
        #    do something here? I want the device ID to be in the file even if it's never appeared online
             pass

    return devices

推荐答案

这是我想出的一个基本示例(删除您已经解决的摘录部分,例如时间转换等)

Here's a basic example I came up with (removing the snippets parts that you have already addressed, such as time conversion, etc)

import json

# Suppose this is your existing json file (I'm keeping it as a string for the sake of the example):
devices_str = '{"deviceIDa":"Wed Nov 08 2017 06:11:27 PM", "deviceIDb":"Wed Nov 08 2017 06:11:27 PM", "deviceIDc":"Tues Nov 07 2017 03:47:01 PM"}'

cmd_output_lines = [
    'deviceIDa:True',
    'deviceIDb:Minion did not return. [No response]',
]
# Generate a dictionary of the devices for current update
devices = dict(
    line.strip().split(':') for line in cmd_output_lines
)
# Filter out the ones currently online, using whatever criteria needed
# In my example, I'm just checking if the response contained a True
online_devices = dict(
    (device_id, resp) for (device_id, resp) in devices.iteritems() if 'True' in resp
#               ^ of course in your case that resp would be current/last seen time
)

# Load existing entries
existing_devices = json.loads(devices_str)

# Update them only overwriting online devices
existing_devices.update(online_devices)

# Final result
print json.dumps(existing_devices)

这将输出:

"deviceIDb": "Wed Nov 08 2017 06:11:27 PM", "deviceIDc": "Tues Nov 07 2017 03:47:01 PM", "deviceIDa": "True"}

如您所见, deviceIDa 是唯一更新的条目( deviceIDb 仍然是现有条目中最后看到的条目)

As you can see, deviceIDa is the only entry that got updated (deviceIDb still has the last seen from the existing entries)

更进一步,如果您想记录最近5次在线时间,则可以使用 defaultdict(list),也可以使用普通的字典,例如:

Taking this a step further, if you want to log the last 5 online times, you can either use a defaultdict(list), or get away with plain dictionaries like so:

>>> d = {1: [2, 3, 4, 5, 6,]}
>>> new = {1: 7, 2: 4} # only one current online time anyway (no need for list here)
>>> for _id, new_online in new.items():
...     d[_id] = (d.get(_id, []) + [new_online])[-5:] # only take the last 5 elements
...     
>>> d
{1: [3, 4, 5, 6, 7], 2: [4]}
>>> 

这篇关于将Python词典保存到文件,并定期更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆