LoginSignup
11

More than 5 years have passed since last update.

Pythonで標準出力をnon-blockingにする

Posted at

標準出力はある程度のバッファが用意されていますがそこが埋まるとブロッキングされます。
ブロッキングするぐらいなら出力を諦めたい状況に遭遇することもあります。
そういう時はこれ

import fcntl, sys, os
fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
fl = fl | os.O_NONBLOCK
fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)

こうすることで

while True:
    try:
        print("hoge" * 100)
    except IOError, (errno, strerror):
        sys.stderr.write("I/O error(%s): %s\n" % (errno, strerror))

などと書いた時

$ ./hoge.py | ./遅いプログラム
I/O error(11): Resource temporarily unavailable
I/O error(11): Resource temporarily unavailable
...

という感じの挙動になります

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
11