我正在使用paramiko登录设备并运行一些命令,然后仅捕获相关输出.代码的相关部分如下所示:
I am using paramiko to login to a device and run some commands and then capture only the relevant output. The relevant portion of the code looks like this:
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现在,我只想要链接状态,所以我这样做了:
Now out of this,I want only the link status,so I did this :
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很好.但是,我想要在列表理解中指定出现的位置,这样我就只能获得关键字Link的第一个,第二个或第n个出现.
Works fine.However,what I want is to specify the occurrence in my list comprehension so that I get only the first,second or nth occurrence of the keyword Link.
推荐答案您有三个选择.
将所有项目存储在列表中,然后使用索引.但这会在内存中创建不必要的列表:
Store all the items in a list and then use indexing. But this will create an unnecessary list in memory:
links = [item for item in stdout.read().splitlines() if 'Link' in item] index = 5 print links[index]或使用 itertools.islice ,并将您在代码中使用的生成器传递给它:
Or use itertools.islice, and pass it the generator created you've used in your code:
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()的原因,因为它们将所有内容读入内存:
Or even better use itertools.islice with the following generator. Here's I am not using either .read() or .splitlines() as they read everything into memory:
links = (item for item in stdout if 'Link' in item) print next(islice(links, index, index+1))如果只想在字符串的开头匹配'Link',也可以使用 item.startswith('Link'),但是如果想要在字符串中的任何地方匹配它,然后忽略它.
You can also use item.startswith('Link') in case you only want to match 'Link' only at the start of the string, but if you want to match it anywhere in the string then ignore this.
更多推荐
使用python查找文本文件中单词出现的第n个实例
发布评论