LoginSignup
29
20

More than 5 years have passed since last update.

Python で stdout/stderr のバッファを無効にするオプション

Posted at

たまに忘れて痛い目をみるので記事にした。

シェルでそのまま実行すると、次のコマンドは書いてあるとおり、予想通りに動くと思う。
1 を出力して、 3 秒待ち、 2 を出力。

$ python -c 'import time; print(1); time.sleep(3); print(2)'
1
2
$

これにパイプを通すとパイプの持つバッファサイズ分が貯まらないと出てこれない。

上の例で示すと、

$ python -c 'import time; print(1); time.sleep(3); print(2)' | cat
1
2
$

単に cat にパイプしただけなのだけど 1 と 2 の行は同じ 3 秒後のタイミングで出てくる。
それっぽく言うと "パイプが詰まってる” というやつ。ファイルに書き出しても同様に遅れて書き出される。

このような挙動を抑止したければ、 -u オプションを使う。

$ python -u -c 'import time; print(1); time.sleep(3); print(2)' | cat
1
2
$

↑ 1 が出てから 3 秒待ち、その後 2 が出てくる。

PYTHONUNBUFFERED 環境変数に空でない文字列を入れても同じ効果が得られる。

29
20
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
29
20