How to remove lines from stdout in python?

前端 未结 2 1929
萌比男神i
萌比男神i 2021-01-21 19:43

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.P         


        
相关标签:
2条回答
  • 2021-01-21 20:16

    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.

    0 讨论(0)
  • 2021-01-21 20:38

    readlines provides all the data

    allLines = [line for line in stdout.readlines()]
    data_no_firstfour = "\n".join(allLines[4:])
    
    0 讨论(0)
提交回复
热议问题