2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python3のprint関数で改行しない方法、sleep併用の時

Posted at

Python3のprint関数で徐々に表示したいとき

引数flushを使います。実践的にはプログレスバー的な表示をしたいときなど。

print("hello", end='', flush=True) 

元々やりたかったのは、こんな感じで進行状況を示す表現。

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

..........ok!

デフォルトで改行時にバッファから一気に出力する設定なので、バッファをフラッシュ、即時出力させる設定に変えるとうまくいきます。こういう、依存関係のあるオプションは落とし穴だ。。

以下、蛇足

Python3のprint関数、普通に書くと改行します。

print("Hey,")
print(" hello")
print(" world!")

Hey,
 hello
 world!

改行したくない時、引数endを設定する方法があります。

print("Hey,", end='')
print(" hello", end='')
print(" world!")

Hey, hello world!


うまくいきました。デフォルト値としてend='\n'が設定されているので、何も指定しないときには改行していたのです。

では、この1行を1ワードづつ区切りながら、くりかえしてみよう。。あれ?

import time
while True:
    print("Hey,", end='')
    time.sleep(1)
    print(" hello", end='')
    time.sleep(1)
    print(" world!")
    time.sleep(1)

Hey, hello world!
3秒後
Hey, hello world!
3秒後
Hey, hello world!
:

1ワードずつ表示したかったのに、3秒毎に、1行全部が表示されます。

これは、デフォルトで「flush='Flase'、バッファに貯めておいて、改行が来たら一気に表示する設定」になっているからです。改行しない設定のために途中経過が見られなくなってしまいました。

では、flush='True'を使って、、

import time
while True:
    print("Hey,", end='', flush='True')
    time.sleep(1)
    print(" hello", end='', flush='True')
    time.sleep(1)
    print(" world!", flush='True')
    time.sleep(1)

思い通り、1ワードづつ区切りながら、くりかえして表示できました。

公式ドキュメントで調べる

Python3のprint関数、他にも引数があります。
https://docs.python.org/ja/3/library/functions.html#print

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)


print("hello") とだけ書くと、こういうこと。
print("hello", sep=' ', end='\n', file=sys.stdout, flush=False)

sepは、separation、コンマ区切りのときの間の文字。デフォルトではスペース。
file= sys.stdoutは、出力先。デフォルトでは、システムの標準出力。

print(1,2,3)
1 2 3

print(1,2,3, sep=' - ')
1 - 2 - 3

以上。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?