Read output line by line in python

4k views Asked by At

hi i want to make ssh connection and parse some datas. Im using paramiko and here is part of my code:

ssh=ssh_pre.invoke_shell()
ssh.send("display ospf peer brief \n")
output = ssh.recv(10000)

everything work until this part

buf=StringIO.StringIO(output)
for lines in buf.read()
    print lines

this code print chars line by line . I want to print lines . what should i do?

1

There are 1 answers

0
David Reeve On

The issue is StringIO.read() returns a string, a sequence of characters, not lines. Try doing this:

buf=StringIO.StringIO(output)
for lines in buf.read().split("\n"):
    print lines

This will split your buffer by newlines and create a list of each line, rather than looping over each individual character in the string.