LoginSignup
2
0

More than 5 years have passed since last update.

引数endを持ったprint関数のあとにtime.sleep()を呼ぶとprintされない

Last updated at Posted at 2016-11-23

問題

0から9までの数字を1秒おきに表示させたい。

count.py
# -*- coding: utf-8 -*-
import time

i = 0
while(i<9):
    print(i, end='')
    time.sleep(1)
    i+=1

実行。

% python3 count.py

...あれ、何もprintされないし何秒たっても何も起こらない...。

試しに

count.py
# -*- coding: utf-8 -*-
import time

i = 0
while(i<10):
    print(i)
    time.sleep(1)
    i+=1

としてみる(引数endを消してみる)と、

% python3 count.py
0
1
2
3
4
5
6
7
8
9
%

1秒おきに表示された。ただ、endは指定したい...。

解決

引数flushを持たせる。

count.py
# -*- coding: utf-8 -*-
import time

i = 0
while(i<10):
    print(i, end='', flush=True)
    time.sleep(1)
    i+=1

実行してみると、

% python3 count.py
0123456789%

うまくいきました。

2
0
0

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
2
0