How do I write output in same place on the console

2019-01-02 22:06发布

I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:

output:

Downloading File FooFile.txt [47%]

I'm trying to avoid something like this:

     Downloading File FooFile.txt [47%]
     Downloading File FooFile.txt [48%]
     Downloading File FooFile.txt [49%]

How should I go about doing this?


Duplicate: How can I print over the current line in a command line application?

8条回答
Explosion°爆炸
2楼-- · 2019-01-02 22:33

Use a terminal-handling library like the curses module:

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-02 22:33

For Python 3xx:

import time
for i in range(10):
    time.sleep(0.2) 
    print ("\r Loading... ".format(i)+str(i), end="")
查看更多
看我几分像从前
4楼-- · 2019-01-02 22:40

Python 2

I like the following:

print 'Downloading File FooFile.txt [%d%%]\r'%i,

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print 'Downloading File FooFile.txt [%d%%]\r'%i,

Python 3

print('Downloading File FooFile.txt [%d%%]\r'%i, end="")

Demo:

import time

for i in range(100):
    time.sleep(0.1)
    print('Downloading File FooFile.txt [%d%%]\r'%i, end="")
查看更多
欢心
5楼-- · 2019-01-02 22:44
#kinda like the one above but better :P

from __future__ import print_function
from time import sleep

for i in range(101):
  str1="Downloading File FooFile.txt [{}%]".format(i)
  back="\b"*len(str1)
  print(str1, end="")
  sleep(0.1)
  print(back, end="")
查看更多
干净又极端
6楼-- · 2019-01-02 22:48
x="A Sting {}"
   for i in range(0,1000000):
y=list(x.format(i))
print(x.format(i),end="")

for j in range(0,len(y)):
    print("\b",end="")
查看更多
放我归山
7楼-- · 2019-01-02 22:52

Print the backspace character \b several times, and then overwrite the old number with the new number.

查看更多
登录 后发表回答