Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2817

[備忘録][一行メモ]Pythonに-uオプション付けたらstdout, stderrがunbufferedになる。teeにパイプするとき便利

$
0
0

タイトルが内容のすべてですが、一応捕捉

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

⇒1が表示され、しばらくしてから2が表示される

sh -c'echo 1; sleep 1; echo 2'

⇒1が表示され、しばらくしてから2が表示される

python -c'import time; print(1); time.sleep(1); print(2) | tee /dev/null

⇒しばらくしてから、1と2が一気に表示される

sh -c'echo 1; sleep 1; echo 2' | tee /dev/null

⇒1が表示され、しばらくしてから2が表示される

なぜPythonでパイプしたときだけ挙動が違う?

Pythonは賢いので、stdout, stderrが端末だったらラインバッファ、そうじゃなければ普通にバッファしてくれる。(いっぱい出力するときは、バッファした方が圧倒的に速い)
ちなみに、Pythonが自分自身でそれをやっているので、stdbufコマンドでは挙動を変えられない。

-uオプションを付けるとunbufferedになる。

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

⇒1が表示され、しばらくしてから2が表示される


Viewing all articles
Browse latest Browse all 2817

Trending Articles