我正在使用 paramiko 登录设备并运行一些命令,然后仅捕获相关输出。代码的相关部分如下所示:
stdin, stdout, stderr = ssh.exec_command('show interface')
print stdout.read()
这给出了以下输出:
Ethernet interface 0:0
Internet address: 171.182.204.207 netmask 255.255.255.0
Internet address: fe80::2d0:83ff:fe06:4c67 prefixlen 64
MTU size: 1500
Link status: configured to full duplex, 1 gigabit/sec network
Member of the bridge: none
Ethernet interface 0:1
Internet address: fe80::2d0:83ff:fe06:4c66 prefixlen 64
MTU size: 1500
Link status: autosensed to full duplex, 1 gigabit/sec network
Member of the bridge: none
现在,我只想要链接状态,所以我这样做了:
stdin, stdout, stderr = ssh.exec_command('show interface')
link = '\n'.join(item for item in stdout.read().splitlines() if 'Link' in item)
print link
现在我明白了:
Link status: configured to full duplex, 1 gigabit/sec network
Link status: autosensed to full duplex, 1 gigabit/sec network
工作正常。但是,我想要的是在我的列表理解中指定出现次数,以便我只获得关键字链接的第一次、第二次或第 n 次出现。
最佳答案
您有三个选择。
将所有项目存储在一个列表中,然后使用索引。但这会在内存中创建一个不必要的列表:
links = [item for item in stdout.read().splitlines() if 'Link' in item]
index = 5
print links[index]
或者使用itertools.islice
,并将您在代码中使用的生成器传递给它:
from itertools import islice
index = 5
links = (item for item in stdout.read().splitlines() if 'Link' in item)
print next(islice(links, index, index+1))
或者甚至更好地将 itertools.islice
与以下生成器一起使用。这是我没有使用 .read()
或 .splitlines()
因为它们将所有内容读入内存:
links = (item for item in stdout if 'Link' in item)
print next(islice(links, index, index+1))
您也可以使用 item.startswith('Link')
以防您只想在字符串的开头匹配 'Link'
,但是如果您想在字符串中的任何地方匹配它然后忽略它。
关于python - 使用python在文本文件中查找单词出现的第n个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24451919/