简体   繁体   English

在python中将嵌套的FOR循环输出存储在2D数组中

[英]Storing a nested FOR loop output in a 2D array in python

I am using paramiko to login to a list of devices and then run a list of commands on each device and then capture the output. 我使用paramiko登录设备列表,然后在每个设备上运行命令列表,然后捕获输出。 The python script is as follows: python脚本如下:

import paramiko

f1 = open('hostfile','r')
f2 = open('commandfile','r')

devices = f1.readlines()
commands = f2.readlines()


for device in devices:
    for command in commands:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(device, username="admin", password="test")
        stdin, stdout, stderr = ssh.exec_command(command)
        output= stdout.read()

f1.close()
f2.close()

What I want to achieve is to store the entire output in a 2 dimensional array as follows: 我想要实现的是将整个输出存储在二维数组中,如下所示:

data = [
('device1', 'output1 for device1', 'output2 for device1', 'output3 for device1'),
('device2', 'output1 for device2', 'output2 for device2', 'output3 for device2'),
('device3', 'output1 for device3', 'output2 for device3', 'output3 for device3')
   ..................
   .................
]

I need to pass this output to an excel sheet using xlwt and hence my need to store the output in this format.. 我需要使用xlwt将此输出传递给excel表,因此我需要以此格式存储输出。

Is this what you want? 这是你想要的吗?

data = []
for device in devices:
    data.append([device])
    for command in commands:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(device, username="admin", password="test")
        stdin, stdout, stderr = ssh.exec_command(command)
        output= stdout.read()
        data[-1].append(output)
    data[-1] = tuple(data[-1])

Some explanation: 一些解释:

what data[-1] and tuple(data[-1]) actually do 什么数据[-1]和元组(数据[-1])实际上做了什么

Note that data is supposed to be a list of tuples. 请注意, data应该是元组列表。

  1. data[-1] refers to the last item of the list data . data[-1]指列表data的最后一项。

  2. data[-1] is built as a list in the inner loop. data[-1]构建为内循环中的列表。 As your specified output structure of data is a list of tuples, the code uses the function tuple() to get a tuple converted from the list data[-1] . 由于您指定的data输出结构是元组列表,因此代码使用函数tuple()来获取从列表data[-1]转换的元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM