Unbuffered Python

python
stdout
unbuffering
asyncio
subprocess
flushing
reading
This article discusses the process of unbuffering Python’s stdout output by utilizing the ‘-u’ option when running a script and modifying the print function to flush output. Additionally, it covers the use of asyncio.create_subprocess_exec for asynchronous reading.
Published

January 6, 2024


When reading bytes asynchronously from stdout using asyncio.create_subprocess_exec, the program has to be unbuffered.

python3 -u <script_path>
# this can only make `print` into unbuffered
import builtins
import copy
old_print = copy.copy(builtins.print)
def custom_print(*args, **kwargs):
if 'flush' not in kwargs:
kwargs['flush'] = True
old_print(*args, **kwargs)
# Override the built-in print function with the custom function
builtins.print = custom_print