multiple prints on the same line in Python

前端 未结 17 2265
独厮守ぢ
独厮守ぢ 2020-11-22 06:06

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installi

相关标签:
17条回答
  • 2020-11-22 06:14

    Most simple:

    Python 3

        print('\r' + 'something to be override', end='')
    

    It means it will back the cursor to beginning, than will print something and will end in the same line. If in a loop it will start printing in the same place it starts.

    0 讨论(0)
  • 2020-11-22 06:16

    Python appends newline as an end to print. Use end=' ' for python3 for print method to append a space instead of a newline. for python2 use comma at end of print statement.

    print("Foo",end=' ')
    print('Bar')
    
    
    0 讨论(0)
  • 2020-11-22 06:17

    This is a very old thread, but here's a very thorough answer and sample code.

    \r is the string representation of Carriage Return from the ASCII character set. It's the same as octal 015 [chr(0o15)] or hexidecimal 0d [chr(0x0d)] or decimal 13 [chr(13)]. See man ascii for a boring read. It (\r) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It's the CR part of CRLF which means Carriage Return and Line Feed.

    print() is a function in Python 3. In Python 2 (any version that you'd be interested in using), print can be forced into a function by importing its definition from the __future__ module. The benefit of the print function is that you can specify what to print at the end, overriding the default behavior of \n to print a newline at the end of every print() call.

    sys.stdout.flush tells Python to flush the output of standard output, which is where you send output with print() unless you specify otherwise. You can also get the same behavior by running with python -u or setting environment variable PYTHONUNBUFFERED=1, thereby skipping the import sys and sys.stdout.flush() calls. The amount you gain by doing that is almost exactly zero and isn't very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.

    And a sample. Note that this runs perfectly in Python 2 or 3.

    from __future__ import print_function
    
    import sys
    import time
    
    ANS = 42
    FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}
    
    for i in range(1, ANS + 1):
        if i in FACTORS:
            print('\r{0:d}'.format(i), end='')
            sys.stdout.flush()
            time.sleep(ANS / 100.0)
    else:
        print()
    
    0 讨论(0)
  • 2020-11-22 06:18

    You should use backspace '\r' or ('\x08') char to go back on previous position in console output

    Python 2+:

    import time
    import sys
    
    def backspace(n):
        sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   
    
    for i in range(101):                        # for 0 to 100
        s = str(i) + '%'                        # string for output
        sys.stdout.write(s)                     # just print
        sys.stdout.flush()                      # needed for flush when using \x08
        backspace(len(s))                       # back n chars    
        time.sleep(0.2)                         # sleep for 200ms
    

    Python 3:

    import time   
    
    def backline():        
        print('\r', end='')                     # use '\r' to go back
    
    
    for i in range(101):                        # for 0 to 100
        s = str(i) + '%'                        # string for output
        print(s, end='')                        # just print and flush
        backline()                              # back to the beginning of line    
        time.sleep(0.2)                         # sleep for 200ms
    

    This code will count from 0% to 100% on one line. Final value will be:

    > python test.py
    100%
    

    Additional info about flush in this case here: Why do python print statements that contain 'end=' arguments behave differently in while-loops?

    0 讨论(0)
  • 2020-11-22 06:18

    print() has a built in parameter "end" that is by default set to "\n" Calling print("This is America") is actually calling print("This is America", end = "\n"). An easy way to do is to call print("This is America", end ="")

    0 讨论(0)
  • 2020-11-22 06:19

    Print has an optional end argument, it is what printed in the end. The default is a newline, but you can change it to empty string. e.g. print("hello world!", end="")

    0 讨论(0)
提交回复
热议问题