multiple prints on the same line in Python

前端 未结 17 2456
独厮守ぢ
独厮守ぢ 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:21

    None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:

    def print_no_newline(string):
        import sys
        sys.stdout.write(string)
        sys.stdout.flush()
    

    To test it:

    import time
    print_no_newline('hello ')
    # Simulate a long task
    time.sleep(2)
    print('world')
    

    "hello " will first print out and flush to the screen before the sleep. After that you can use standard print.

提交回复
热议问题