2024-01-06
Unbuffered Python

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

1
2
python3 -u <script_path>

1
2
3
4
5
6
7
8
9
10
11
# 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

Read More