在Python中剥离特定行并存储到变量中
我有一个命令的输出,看起来像这样:
asdf> show status
Ok
Will be patched
fgh>
Need this
>
我想做的是去掉每一行中包含 ">" 的内容,并把结果存储在一个变量(叫做 result)里,这样当我执行 print result 时,我能得到:
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 个回答
1
我觉得在这种情况下,用 filter
会更容易理解。
filter(lambda s: '>' not in s, stdout.read().splitlines())
2
result = '\n'.join(item for item in stdout.read().splitlines() if '>' not in item)
你需要这样做。当你使用 print(result)
时,它会按照你问题中指定的方式输出结果。