代码之家  ›  专栏  ›  技术社区  ›  Ruben Quinones

如何在python中从stdout中删除行?

  •  2
  • Ruben Quinones  · 技术社区  · 15 年前

    我有一个程序,它使用paramiko通过ssh获取一些数据:

    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\u stdout\u主机上删除前4行。我尝试过使用StringIO来使用这样的readlines:

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

    2 回复  |  直到 11 年前
        1
  •  2
  •   pyfunc    15 年前

    readlines提供所有数据

    allLines = [line for line in stdout.readlines()]
    data_no_firstfour = "\n".join(allLines[4:])
    
        2
  •  3
  •   Community Mohan Dere    9 年前

    如何在python中从stdout中删除行?

    Python控制台窗口

    另请参见: here here

    而不是使用 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='')
    

    对于3.0以下的Python版本,请将 from __future__ import print_function 在您的脚本/模块的顶部。

    请注意,此解决方案适用于stdout Python控制台窗口,例如,通过右键单击并选择“open with->Python”来运行脚本。它不适用于SciTe、Idle、Eclipse或其他带有合并控制台窗口的编辑器。我在等解决办法 在这里