LoginSignup
138

More than 5 years have passed since last update.

コンソールへの出力を上書きしてゆく方法

Posted at

カウントダウンをしたいときとか、普通にprintを使って

for i in range(100):
    print i

とするとコンソール上に

1
2
3
4
5

と、縦長に出力されてしまう。
これだと見づらいので、インストールの時に表示される進度メーターのように、次の数字を出力する際に前の出力が消えて そこに次の数字が現れてほしい

上書きする場合

import sys, time
for num, i in enumerate(range(100)):
    sys.stdout.write("\r%d" % num)
    sys.stdout.flush()
    time.sleep(0.01)

sys.stdout.writeの\rがキモっぽい。これがないと上書きされない。

追記してゆく場合

import sys, time
for i in range(100):
    sys.stdout.write("=")
    sys.stdout.flush()
    time.sleep(0.01)

これで無駄な出力で画面がうめつくされるのを防げるわけです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
138