LoginSignup
6

More than 5 years have passed since last update.

python > print > 処理終了時にしかリダイレクトされない? > -u 付きで実行する

Last updated at Posted at 2015-10-26
動作確認
Raspberry Pi2 (raspbian)
MacOS X 10.8.5

pythonでの出力

以下のコードを用意

hello.py
#!/usr/bin/env python
import time

print "hello"

for x in range(0,60):
    print x
    time.sleep(1)

以下のように実行

$ ./hello.py > log.tmp

別のターミナルで以下を実行

$ tail -f log.tmp

上記を行った時、log.tmpの中身の更新は60回のprintが終わった後になっているようだ。

stdoutで見た時は毎秒表示されるが、ファイル出力の場合は毎秒出力されない。

bashでの出力

代わりにbashのスクリプトを用意

test-exec
#!/usr/bin/env bash

for x in $(seq 1 60)
do
  echo $x
  sleep 1
done

こちらを実行した場合は、毎秒ファイル出力される。

疑問

pythonのprint文で毎秒ファイル出力させるにはどうするのだろうか。

print以外のファイル書込み命令を使えばいいのかもしれないが、ファイルのリダイレクトと組合せられる方法を調べないと。

DHT11で温度、湿度が測れてもファイル出力時にtail -fで見れないのが惜しい。

解決

python実行時に -u オプションを指定すればいいようだ。

hello.py
#!/usr/bin/env python -u
import time

print "hello"

for x in range(0,60):
    print x
    time.sleep(1)

上記の指定 #!/usr/bin/env python -uでMacOSX上では動いた。
一方で、raspberry Pi2では-uオプションがないというようなエラーとなった。
#!/usr/bin/python -uにしたら動いた。

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
What you can do with signing up
6