How to remove lines from stdout in python?

廉价感情. 提交于 2019-12-31 02:49:06

问题


I have a program that grabs some data through ssh using paramiko:

ssh = paramiko.SSHClient()

ssh.connect(main.Server_IP, username=main.Username, password=main.Password)

ssh_stdin_host, ssh_stdout_host, ssh_stderr_host =ssh_session.exec_command(setting.GetHostData)

I would like to remove the first 4 lines from ssh_stdout_host. I've tried using StringIO to use readlines like this:

output = StringIO("".join(ssh_stdout_host))
data_all = output.readlines()

But I'm lost after this. What would be a good approach? Im using python 2.6.5. Thanks.


回答1:


readlines provides all the data

allLines = [line for line in stdout.readlines()]
data_no_firstfour = "\n".join(allLines[4:])



回答2:


How to remove lines from stdout in python?

(this is a general answer for removing lines from the stdout Python console window, and has nothing to do with specific question involving paramiko, ssh etc)

see also: here and here

Instead of using the print command or print() function, use sys.stdout.write("...") combined with sys.stdout.flush(). To erase the written line, go 'back to the previous line' and overwrite all characters by spaces using sys.stdout.write('\r'+' '*n), where n is the number of characters in the line.


a nice example says it all:

import sys, time

print ('And now for something completely different ...')
time.sleep(0.5)

msg = 'I am going to erase this line from the console window.'
sys.stdout.write(msg); sys.stdout.flush()
time.sleep(1)

sys.stdout.write('\r' + ' '*len(msg))
sys.stdout.flush()
time.sleep(0.5)

print('\rdid I succeed?')
time.sleep(1)

edit instead of sys.stdout.write(msg); sys.stdout.flush(), you could also use

print(msg, end='')

For Python versions below 3.0, put from __future__ import print_function at the top of your script/module for this to work.

Note that this solution works for the stdout Python console window, e.g. run the script by right-clicking and choosing 'open with -> python'. It does not work for SciTe, Idle, Eclipse or other editors with incorporated console windows. I am waiting myself for a solution for that here.



来源:https://stackoverflow.com/questions/3732928/how-to-remove-lines-from-stdout-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!