从输出中剥离特定行并存储在python中的变量中

时间:2014-04-16 14:55:23

标签: python string strip

我有一个命令的输出,如下所示:

asdf> show status
Ok
Will be patched
fgh>
Need this
>

我想要做的是剥离包含“>”的每一行的输出并将输出存储在变量(结果)中,这样在发出打印结果时,我得到:

Ok
Will be patched
Need this

这就是我目前所拥有的:

offending = [">"]
#stdout has the sample text
for line in stdout.readlines():
    if not True in [item in line for item in offending]:
        print line

目前它只是打印线。我希望它存储在一个变量中,以便打印变量打印我想要的整个输出。

编辑:为了更清楚我正在做什么,来自命令行解释器的结果:

Python 2.7.3 (default, Aug  1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>>>> import paramiko
>>> offending = [">"]
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> conn=ssh.connect('10.12.23.34', username='admin', password='admin', timeout=4)
>>> stdin, stdout, stderr = ssh.exec_command('show version')
>>> print stdout.read()

bcpxyrch1>show version
Version: SGOS 6.2.12.1 Proxy Edition
Release id: 104304
UI Version: 6.2.12.1 Build: 104304
Serial number: 3911140082
NIC 0 MAC: 00D083064C67
bcpxyrch1>

>>> result = '\n'.join(item for item in stdout if offending not in item)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
TypeError: 'in <string>' requires string as left operand, not list
>>>

2 个答案:

答案 0 :(得分:2)

result = '\n'.join(item for item in stdout.read().splitlines() if '>' not in item)

这就是你需要做的。当您print(result)时,它将完全按照您的问题中的指定输出。

答案 1 :(得分:1)

我认为在这种情况下使用filter更具可读性。

filter(lambda s: '>' not in s, stdout.read().splitlines())