kbirds30
kbirds30

Reputation: 49

return all output from a for loop in python 3

I trying to return all results from a loop. the out is just strings of data from basic show commands off cisco devices. Both devices print their output just fine but when i return the for loop I only get the output from the last device in the list.

I have tried a dict list on top of the for loop but the output is string i guess so it does not accept the information.

    # Juniper Normalize the data for command line interface
    juniper_command = '"({})"'.format('|'.join(src_a + src_p + dst_a + dst_p))
    # Device IP list
    fw_a = ['10.90.2.20', '10.90.1.10']

    try:
        result = ()
        for ip in fw_a:
            if "true" in str(p_show):
                device = {"device_type": "juniper_junos", "username": username, "host": ip, "password": password}
                connection = netmiko.ConnectHandler(**device)
                connection.find_prompt(delay_factor=2)
                time.sleep(1)
                connection.enable()
                resp = connection.send_command(
                    'show configuration | display xml | match ' + str(juniper_command), delay_factor=2)
                print(ip + '\n' + resp)
                result = resp

        return result

My expected results would be to return all data from the devices in the list.

Upvotes: 0

Views: 4879

Answers (2)

kbirds30
kbirds30

Reputation: 49

Thanks for all the help from ChocolateAndChees. i go this solved with adding result = [] on the top of the loop then result.append(resp) then return str(result)

Upvotes: 1

ChocolateAndCheese
ChocolateAndCheese

Reputation: 989

Everytime you run through the loop, you call result = resp, which overwrites the value of result with resp. So, at the end of the loop, the value of result is just the value of resp from the last loop.

If you want to get a list of of all of the values of resp from each loop iteration, it might make sense to make result a list (use result = [] instead of result = ()), and then instead of saying result = resp, you could instead say result.append(resp).

Edit: It looks like you need to return a tuple, so as mentioned in the comment by Hans, you can use return tuple(result) or return tuple(r for r in result).

Upvotes: 2

Related Questions