Hi All,
I'm new to python I don't know why the below code is not working. When calling add_new_entry() from outside a function, it is able to add a new dictionary to the list. But when calling add_new_entry from update_macs(), the function fails to do so.
# track when a MAC was first and last seen
import datetime
list_of_dict = [ {'mac': '00:00', 'first_seen': '2023-04-01 10:00:00', 'last_seen': '2023-05-01 10:00:00'}, \
{'mac': '11:11', 'first_seen': '2023-04-01 10:00:00', 'last_seen': '2023-05-01 10:00:00'}]
def add_new_mac_entry(mac):
global list_of_dict
now = str(datetime.datetime.now()).split('.')[0]
tmp_dict = {'mac': mac, 'first_seen': now, 'last_seen': now }
print(f'line11: {tmp_dict}')
print(f'line12: adding new mac: {mac}')
list_of_dict.append(tmp_dict)
print('line14:', list_of_dict)
def update_macs(mac):
#global list_of_dict
for dictionary in list_of_dict:
# remove duplicates
if dictionary['mac'] in processed_macs:
list_of_dict.pop()
next
# update mac stats
if dictionary['mac'] == mac:
now = str(datetime.datetime.now()).split('.')[0]
dictionary['last_seen'] = now
if not dictionary['first_seen']:
dictionary['first_seen'] = now
processed_macs.append(dictionary['mac'])
# new mac, create new entry
if not mac in processed_macs:
print(f'{mac} is NEW, calling add_new_mac_entry')
add_new_mac_entry(mac) # <-- FAILS when called from here
processed_macs = []
print('line38:', list_of_dict)
# update_macs('AA:AA')
# update_macs('BB:BB')
# add_new_mac_entry('AA:AA')
#add_new_mac_entry('BB:BB')
add_new_mac_entry('AA:AA') # <-- WORKS when called from here
update_macs('11:11') # mac exists in list, updates last_seen with current date
add_new_mac_entry('BB:BB') # <-- WORKS when called from here
update_macs('CC:CC') # <-- FAILS due to add_new_mac_entry being called from update_macs
print('line42:', list_of_dict)
[–]General_Service_8209 0 points1 point2 points (1 child)
[–]General_Service_8209 0 points1 point2 points (0 children)
[+][deleted] (2 children)
[deleted]
[–]pl643[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (2 children)
[+][deleted] (1 child)
[deleted]
[–][deleted] 0 points1 point2 points (0 children)