如何在Jupyter Notebook中重定义Python3 print函数使flush默认设为True?
print() Default to flush=True Your initial attempt at redefining print will cause infinite recursion (since your custom function calls itself directly), but there are two reliable ways to achieve what you want:
Method 1: Use functools.partial
This is the simplest approach—we can create a wrapped version of the built-in print that sets flush=True as the default:
from functools import partial # Override print with our version that flushes by default print = partial(print, flush=True)
Now any call to print() will automatically include flush=True unless you explicitly set flush=False in the arguments.
Method 2: Create a Custom Wrapper Function
If you want more flexibility (like letting users override the flush default when needed), write a wrapper that preserves access to the original print function:
# Save a reference to the original print before overriding it original_print = print def print(*args, **kwargs): # Set flush to True only if it's not already specified kwargs.setdefault('flush', True) original_print(*args, **kwargs)
This way, if someone calls print("Hello", flush=False), the custom function will respect that explicit False value, while using True by default.
Why This Fixes Your Jupyter Notebook Issue
The out-of-order output between print() and input() is a classic buffer problem. By default, Python buffers standard output—meaning it holds onto printed text until a newline or buffer flush occurs. In Jupyter, this can lead to race conditions where input() triggers a flush before print() has written its content, messing up the order. Setting flush=True forces the print statement to send its content to the output immediately, ensuring your messages appear in the expected sequence every time.
内容的提问来源于stack exchange,提问作者Jo Simon

