![]() |
list is printing incorrectly.. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: list is printing incorrectly.. (/thread-18444.html) |
list is printing incorrectly.. - anna - May-18-2019 Hi All, Below is the my function, which telnet to devices post checking reachability, after login, I am gathering interface status and if interface name start with Fa0 and status in 'up', storing to dict, later appended to list. However post checking interface and status, its printing correctly, but list is printing incorrect details. def open_telnet_new(reachable_sw): timeout = 120 sr_no = 0 switch_port_dict = {} interface_list = [] try: session = telnetlib.Telnet(reachable_sw, 23, timeout) # session.set_debuglevel(2) time.sleep(1) session.read_until(b"Username:") session.write((user+"\r").encode('ascii')) time.sleep(2) session.read_until(b"Password:",2) session.write((password + "\r").encode('ascii')) time.sleep(2) session.read_until(b">") session.write("term len 0".encode('ascii') + b"\r") session.read_until(b">") session.write("show int desc".encode('ascii') + b"\r") #output = session.read_all() output = session.read_until(">".encode('ascii'), timeout ) #print(type(output)) for line in output.decode('utf-8').split('\n')[2:]: if '>' in line: continue else: newline = re.sub('\s{2,}',' ',line).replace('admin down','admin_down').strip().split(' ') interface = newline[0] status = newline[1] if interface.startswith('Fa0') and status == 'up': print(reachable_sw,interface,status) #if status =='up': #print('yes') switch_port_dict['switch_ip'] = reachable_sw switch_port_dict['port'] = interface interface_list.append(switch_port_dict) #interface_list.append(reachable_sw) #print(reachable_sw,interface_list) else: continue for interfaces in interface_list: #for ports in interfaces: print(interfaces['switch_ip'],interfaces['port'])output while printing list which is incorrect. correct output without list.
RE: list is printing incorrectly.. - ichabod801 - May-18-2019 You are appending the same dictionary every time. Unless you do an explicit copy of a dictionary, whenever you modify the dictionary, you modify every other instance of the dictionary you left laying about. That's because the variables are just pointing to the (same) dictionary, not hosting independent versions of it. I would just condense lines 34-36 into one line: interface_list.append({'switch_ip': reachable_sw, 'port': interface}) .
|