Make standard output non-blocking in Python

Standard output has some buffer, but it is blocked when it is filled. You may come across situations where you want to give up output as much as blocking. In such a case this

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)

By doing this

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

When I wrote

$ ./hoge.py | ./Slow program
I/O error(11): Resource temporarily unavailable
I/O error(11): Resource temporarily unavailable
...

It will behave like

Recommended Posts

Make standard output non-blocking in Python
Japanese output in Python
How to output "Ketsumaimo" as standard output in Python
Don't make test.py in Python!
Transposed matrix in Python standard
Make a bookmarklet in Python
Make Opencv available in Python
Make python segfault in 2 lines
Read Fortran output in python
Get standard output in real time with Python subprocess
Output log in JSON format with Python standard logging
Make python segfault in one line
Output 2017 Premium Friday list in Python
Change the standard output destination to a file in Python
Make python segfault in three lines
Export and output files in Python
Read the standard output of a subprocess line by line in Python
Data input / output in Python (CSV, JSON)
Make ASCII art GIF animation in Python
Output tree structure of files in Python
UnicodeEncodeError struggle with standard output of python3
Let's make a combination calculation in Python
Make cron-like jobs run regularly in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
python learning output
[Python] Standard input
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python