Python: multiple prints on the same line

2018-12-31 17:51发布

I want to run a script, which basicly shows things like:

Installing XXX...               [DONE]

Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the same line.

Any ideas?

14条回答
临风纵饮
2楼-- · 2018-12-31 18:21

sys.stdout.write will print without return carriage

import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")

http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines

查看更多
素衣白纱
3楼-- · 2018-12-31 18:21

Most simple:

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.

查看更多
美炸的是我
4楼-- · 2018-12-31 18:24

Here a 2.7-compatible version derived from the 3.0 version by @Vadim-Zin4uk:

Python 2

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print '{0}\r'.format(s),                # just print and flush

    time.sleep(0.2)

For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn't make use of the integer argument and could probably be done away with altogether.

Python 3

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print('{0}\r'.format(s), end='')        # just print and flush

    time.sleep(0.2)                         # sleep for 200ms

Both have been tested and work.

查看更多
只靠听说
5楼-- · 2018-12-31 18:25

Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.

查看更多
深知你不懂我心
6楼-- · 2018-12-31 18:31

I found this solution, and it's working on Python 2.7

# Working on Python 2.7 Linux

import time
import sys


def backspace(n):
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(string)
    backspace(len(s))                       # back for n chars
    sys.stdout.flush()
    time.sleep(0.2)                         # sleep for 200ms
查看更多
泛滥B
7楼-- · 2018-12-31 18:35

You can simply use this:

print 'something',
...
print ' else',

and the output will be

something else

no need to overkill by import sys. Pay attention to comma symbol at the end.

Python 3+ print("some string", end=""); to remove the newline insert at the end. Read more by help(print);

查看更多
登录 后发表回答