Reputation: 1
I am trying to put a list of keys which is a csv output of a python(show ip interface brief) command into a table using some sort of textfsm/tabulate tool. I used tabulate with headers to try and put it in a table but it looks like the ouput(fig.1) in the next section. I expected something with the headers 'intf', 'ipaddr', 'stats', 'proto'
, and each corresponding descriptions to be listed below them. Any help would be a lifesaver!
fig.1-Output
intf ipaddr
stats proto
{'intf': 'GigabitEthernet1/0/21', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'} {'intf': 'GigabitEthernet1/0/22', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'} {'intf': 'GigabitEthernet1/0/23', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'} {'intf': 'GigabitEthernet1/0/24', 'ipaddr': 'unassigned', 'status': 'up', 'proto': 'up'} {'intf': 'GigabitEthernet1/0/25', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'} {'intf': 'GigabitEthernet1/0/26', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'}
My code for this looks like this:
from netmiko import ConnectHandler
import pandas
import csv
from tabulate import tabulate
cisco1 = {
"device_type": "cisco_ios",
"host": "cisco",
"username": "cisco",
"password": "cisco",
}
command = "show ip interface brief"
with ConnectHandler(**cisco1) as net_connect:
output = net_connect.send_command(command, use_textfsm=True)
dataset = [output]
#df = pandas.DataFrame(output)
#df.to_csv('new.csv', index=True, header=True)
headers = ['intf', 'ipaddr', 'stats', 'proto']
print(tabulate(dataset, headers = headers))
Expectation: I expected something with the headers 'intf', 'ipaddr', 'stats', 'proto', and each corresponding descriptions to be listed below them.
Upvotes: 0
Views: 73
Reputation: 11
The tabular module requires that the input data be a list of lists... but the output actually contains a list of dictionaries. So, if I understand you, the question at the end is how to transform a list of dictionaries to a tabulated format...
from tabulate import tabulate
output = [{'intf': 'GigabitEthernet1/0/21', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'},
{'intf': 'GigabitEthernet1/0/22', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'}]
You must first transform the list of dictionaries into a list of lists. There are many ways to do this in Python... but this is one.
output_list_of_list = [ list(dict.values()) for dict in output]
Now you can view in tabular table format...
headers = ['intf', 'ipaddr', 'stats', 'proto']
tabulated_table = tabulate(output_list_of_list, headers)
print(tabulated_table)
Upvotes: 0