Print in one line dynamically

2018-12-31 05:29发布

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

Specifically, suppose I have:

for item in range(1,100):
    print item

The result is:

1
2
3
4
.
.
.

How get this to instead look like:

1 2 3 4 5 ...

Even better, is it possible to print the single number over the last number, so only one number is on the screen at a time?

17条回答
宁负流年不负卿
2楼-- · 2018-12-31 06:00

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

查看更多
牵手、夕阳
3楼-- · 2018-12-31 06:02

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

In general, the way to do that is with terminal control codes. This is a particularly simple case, for which you only need one special character: U+000D CARRIAGE RETURN, which is written '\r' in Python (and many other languages). Here's a complete example based on your code:

from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\n") # move the cursor to the next line

Some things about this that may be surprising:

  • The \r goes at the beginning of the string so that, while the program is running, the cursor will always be after the number. This isn't just cosmetic: some terminal emulators get very confused if you do it the other way around.
  • If you don't include the last line, then after the program terminates, your shell will print its prompt on top of the number.
  • The stdout.flush is necessary on some systems, or you won't get any output. Other systems may not require it, but it doesn't do any harm.

If you find that this doesn't work, the first thing you should suspect is that your terminal emulator is buggy. The vttest program can help you test it.

You could replace the stdout.write with a print statement but I prefer not to mix print with direct use of file objects.

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 06:03
In [9]: print?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function print>
Namespace:      Python builtin
Docstring:
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.
查看更多
何处买醉
5楼-- · 2018-12-31 06:05

Another answer that I'm using on 2.7 where I'm just printing out a "." every time a loop runs (to indicate to the user that things are still running) is this:

print "\b.",

It prints the "." characters without spaces between each. It looks a little better and works pretty well. The \b is a backspace character for those wondering.

查看更多
美炸的是我
6楼-- · 2018-12-31 06:07

If you just want to print the numbers, you can avoid the loop.

# python 3
import time

startnumber = 1
endnumber = 100

# solution A without a for loop
start_time = time.clock()
m = map(str, range(startnumber, endnumber + 1))
print(' '.join(m))
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('took {0}ms\n'.format(timetaken))

# solution B: with a for loop
start_time = time.clock()
for i in range(startnumber, endnumber + 1):
    print(i, end=' ')
end_time = time.clock()
timetaken = (end_time - start_time) * 1000
print('\ntook {0}ms\n'.format(timetaken))

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 took 21.1986929975ms

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 took 491.466823551ms

查看更多
长期被迫恋爱
7楼-- · 2018-12-31 06:08

change

print item

to

print "\033[K", item, "\r",
sys.stdout.flush()
  • "\033[K" clears to the end of the line
  • the \r, returns to the beginning of the line
  • the flush statement makes sure it shows up immediately so you get real-time output.
查看更多
登录 后发表回答