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:09

To make the numbers overwrite each other, you can do something like this:

for i in range(1,100):
    print "\r",i,

That should work as long as the number is printed in the first column.

EDIT: Here's a version that will work even if it isn't printed in the first column.

prev_digits = -1
for i in range(0,1000):
    print("%s%d" % ("\b"*(prev_digits + 1), i)),
    prev_digits = len(str(i))

I should note that this code was tested and works just fine in Python 2.5 on Windows, in the WIndows console. According to some others, flushing of stdout may be required to see the results. YMMV.

查看更多
低头抚发
3楼-- · 2018-12-31 06:09
for i in xrange(1,100):
  print i,
查看更多
零度萤火
4楼-- · 2018-12-31 06:10

Change print item to:

  • print item, in Python 2.7
  • print(item, end=" ") in Python 3

If you want to print the data dynamically use following syntax:

  • print(item, sep=' ', end='', flush=True) in Python 3
查看更多
临风纵饮
5楼-- · 2018-12-31 06:10

Like the other examples,
I use a similar approach but instead of spending time calculating out the last output length, etc,

I simply use ANSI code escapes to move back to the beginning of the line and then clear that entire line before printing my current status output.

import sys

class Printer():
    """Print things to stdout on one line dynamically"""
    def __init__(self,data):
        sys.stdout.write("\r\x1b[K"+data.__str__())
        sys.stdout.flush()

To use in your iteration loop you would just call something like:

x = 1
for f in fileList:
    ProcessFile(f)
    output = "File number %d completed." % x
    Printer(output)
    x += 1   

See more here

查看更多
素衣白纱
6楼-- · 2018-12-31 06:13

for Python 2.7

for x in range(0, 3):
    print x,

for Python 3

for x in range(0, 3):
    print(x, end=" ")
查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 06:17

I think a simple join should work:

nl = []
for x in range(1,10):nl.append(str(x))
print ' '.join(nl)
查看更多
登录 后发表回答