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'}
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':''}
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.
Relevant code:
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