将 print flush=True 设置为默认值?

Set print flush=True to default?

我知道您可以通过像这样设置 flush=True 在打印语句后刷新:

print("Hello World!", flush=True)

但是,对于打印很多的情况,手动将每个打印设置为 flush=True 是很麻烦的。有没有办法将 Python 3.x 的默认值设置为 flush=True?我在想类似于 numpy 使用 numpy.set_printoptions.

给出的打印选项的东西

你可以这样使用:

def decorator(func):
    printer = func
    def wrapped(*args):
        printer(*args, end=' *\n', flush=True)
    return wrapped

print = decorator(print)

for i in range(5):
    print(i)
0 *
1 *
2 *
3 *
4 *

您可以使用 partial:

from functools import partial
print_flushed = partial(print, flush=True)
print_flushed("Hello world!")

来自文档:

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature.