2010-09-17 23 views
2

我有一個程序,通過ssh使用的paramiko抓住一些數據:如何從python中刪除標準輸出行?

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) 

我想從ssh_stdout_host取出前4行。我試過使用StringIO來使用這樣的readlines:

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

但是我在此之後失去了。什麼是一個好方法?我使用python 2.6.5。謝謝。

回答

2

readlines方法提供了所有的數據

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

谷歌對於「python list slice syntax」來說,你可以通過這種方式列出所有酷炫的東西。 – Powertieke 2010-09-17 06:09:48

+0

另外我用Paramiko和我不知道stdout.readlines()返回一個迭代器或行的完整列表。上面的代碼的第一行如果返回一個列表將會是非常糟糕的。但我想這確保了代碼不會出錯。 – pyfunc 2010-09-17 06:13:53

+0

謝謝!正是我在找的東西。 – 2010-09-17 06:28:56

3

如何從標準輸出在python刪除線?

(這是從標準輸出Python的控制檯窗口刪除線籠統的回答,並沒有任何具體的問題,涉及的paramiko,SSH等)

還看到:herehere

而不是使用print命令或print()函數,使用sys.stdout.write("...")結合sys.stdout.flush()。要刪除寫入的行,請返回上一行並使用sys.stdout.write('\r'+' '*n)用空格覆蓋所有字符,其中n是行中的字符數。


一個很好的例子就說明了一切:

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) 

編輯 代替sys.stdout.write(msg); sys.stdout.flush(),你也可以使用

print(msg, end='') 

對於Python版本低於3.0,把from __future__ import print_function在這個工作的腳本/模塊的頂部。

請注意,此解決方案適用於stdout Python控制檯窗口,例如,通過右鍵單擊並選擇'open with - > python'來運行腳本。它不適用於SciTe,Idle,Eclipse或其他具有集成控制檯窗口的編輯器。我正在等待自己尋求解決方案here