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.
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
= copy.copy(builtins.print)
old_print def custom_print(*args, **kwargs):
if 'flush' not in kwargs:
'flush'] = True
kwargs[*args, **kwargs)
old_print(# Override the built-in print function with the custom function
print = custom_print builtins.