Print in one line dynamically

后端 未结 20 3201
梦谈多话
梦谈多话 2020-11-21 23:32

I would like to make several statements that give standard output without seeing newlines in between statements.

Specifically, suppose I have:

for it         


        
20条回答
  •  礼貌的吻别
    2020-11-21 23:41

    "By the way...... How to refresh it every time so it print mi in one place just change the number."

    It's really tricky topic. What zack suggested ( outputting console control codes ) is one way to achieve that.

    You can use (n)curses, but that works mainly on *nixes.

    On Windows (and here goes interesting part) which is rarely mentioned (I can't understand why) you can use Python bindings to WinAPI (http://sourceforge.net/projects/pywin32/ also with ActivePython by default) - it's not that hard and works well. Here's a small example:

    import win32console, time
    
    output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
    info = output_handle.GetConsoleScreenBufferInfo()
    pos = info["CursorPosition"]
    
    for i in "\\|/-\\|/-":
        output_handle.WriteConsoleOutputCharacter( i, pos )
        time.sleep( 1 )
    

    Or, if you want to use print (statement or function, no difference):

    import win32console, time
    
    output_handle = win32console.GetStdHandle(  win32console.STD_OUTPUT_HANDLE )
    info = output_handle.GetConsoleScreenBufferInfo()
    pos = info["CursorPosition"]
    
    for i in "\\|/-\\|/-":
        print i
        output_handle.SetConsoleCursorPosition( pos )
        time.sleep( 1 )
    

    win32console module enables you to do many more interesting things with windows console... I'm not a big fan of WinAPI, but recently I realized that at least half of my antipathy towards it was caused by writing WinAPI code in C - pythonic bindings are much easier to use.

    All other answers are great and pythonic, of course, but... What if I wanted to print on previous line? Or write multiline text, than clear it and write the same lines again? My solution makes that possible.

提交回复
热议问题