186

私はPythonを初めて使用し、FTPサーバーなどからのファイルのダウンロードを自動化するスクリプトをいくつか書いています。ダウンロードの進行状況を表示したいのですが、次のように同じ位置に留まりたいです:

出力:

ファイル FooFile.txt のダウンロード [47%]

私はこのようなことを避けようとしています:

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

これを行うにはどうすればよいですか?


複製: コマンドラインアプリケーションで現在の行を上書きするにはどうすればよいですか?

4

9 に答える 9

276

キャリッジ リターンを使用することもできます。

sys.stdout.write("Download progress: %d%%   \r" % (progress) )
sys.stdout.flush()
于 2009-02-05T18:22:47.683 に答える
54

Python 2

私は次が好きです:

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

デモ:

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="")

デモ:

import time

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

Python3を搭載したPyCharmデバッガコンソール

# On PyCharm Debugger console, \r needs to come before the text.
# Otherwise, the text may not appear at all, or appear inconsistently.
# tested on PyCharm 2019.3, Python 3.6

import time

print('Start.')
for i in range(100):
    time.sleep(0.02)
    print('\rDownloading File FooFile.txt [%d%%]'%i, end="")
print('\nDone.')
于 2009-02-05T19:29:23.197 に答える
28

curses モジュールのような端末処理ライブラリを使用します。

curses モジュールは、ポータブルで高度な端末処理のデファクト スタンダードである curses ライブラリへのインターフェイスを提供します。

于 2009-02-05T18:19:09.313 に答える
16

バックスペース文字\bを数回出力してから、古い番号を新しい番号で上書きします。

于 2009-02-05T18:14:06.297 に答える
8
#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="")
于 2011-11-02T04:14:27.630 に答える